<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>Spring笔记一 | 净土</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="Spring">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring笔记一">
<meta property="og:url" content="http://howiefh.github.io/2015/03/06/spring-note-1/index.html">
<meta property="og:site_name" content="净土">
<meta property="og:description" content="Spring">
<meta property="og:image" content="http://fh-1.qiniudn.com/spring3-modules.png">
<meta property="og:updated_time" content="2015-07-17T03:44:51.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring笔记一">
<meta name="twitter:description" content="Spring">
  
    <link rel="alternative" href="/atom.xml" title="净土" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.ico">
  
  <link href="http://fonts.useso.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="/css/style.css" type="text/css">
  
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-40492061-1', 'auto');
ga('send', 'pageview');

</script>


  
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?56d2899c5e919fbf4a7b00de5d1c31dd";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>


</head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">净土</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/" id="subtitle">乐不在外而在心，心以为乐，则是境皆乐；心以为苦，则无境不苦。</a>
        </h2>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-github-link" class="nav-icon" href="https://github.com/howiefh" title="Github" target="_blank"></a>
        
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed" target="_blank"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://howiefh.github.io"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-spring-note-1" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    
<a href="/2015/03/06/spring-note-1/" class="article-date">
  <time datetime="2015-03-06T08:09:20.000Z" itemprop="datePublished">2015-03-06</time>
</a>


    
  <div class="article-category">
    <a class="article-category-link" href="/categories/JavaEE/">JavaEE</a>►<a class="article-category-link" href="/categories/JavaEE/Spring/">Spring</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      Spring笔记一
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
		
		<div id="toc" class="toc-article">
			<h2 class="toc-title"><span>Contents</span></h2>
		
			<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring核心机制：依赖注入"><span class="toc-number">1.</span> <span class="toc-text">Spring核心机制：依赖注入</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#设值注入"><span class="toc-number">1.1.</span> <span class="toc-text">设值注入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#构造注入"><span class="toc-number">1.2.</span> <span class="toc-text">构造注入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#两种注入方式的对比"><span class="toc-number">1.3.</span> <span class="toc-text">两种注入方式的对比</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring容器"><span class="toc-number">2.</span> <span class="toc-text">Spring容器</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#使用ApplicationContext"><span class="toc-number">2.1.</span> <span class="toc-text">使用ApplicationContext</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ApplicationContext的国际化支持"><span class="toc-number">2.2.</span> <span class="toc-text">ApplicationContext的国际化支持</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ApplicationContext的事件机制"><span class="toc-number">2.3.</span> <span class="toc-text">ApplicationContext的事件机制</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#让Bean获取Spring容器"><span class="toc-number">2.4.</span> <span class="toc-text">让Bean获取Spring容器</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring容器中的Bean"><span class="toc-number">3.</span> <span class="toc-text">Spring容器中的Bean</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Bean的基本定义"><span class="toc-number">3.1.</span> <span class="toc-text">Bean的基本定义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#容器中Bean的作用域"><span class="toc-number">3.2.</span> <span class="toc-text">容器中Bean的作用域</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#配置依赖"><span class="toc-number">3.3.</span> <span class="toc-text">配置依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#设置普通属性值"><span class="toc-number">3.4.</span> <span class="toc-text">设置普通属性值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#配置合作者"><span class="toc-number">3.5.</span> <span class="toc-text">配置合作者</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用自动装配注入合作者bean"><span class="toc-number">3.6.</span> <span class="toc-text">使用自动装配注入合作者bean</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#byName规则"><span class="toc-number">3.6.1.</span> <span class="toc-text">byName规则</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#byType规则"><span class="toc-number">3.6.2.</span> <span class="toc-text">byType规则</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#注入嵌套Bean"><span class="toc-number">3.7.</span> <span class="toc-text">注入嵌套Bean</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#list、set、map、props"><span class="toc-number">3.8.</span> <span class="toc-text">list、set、map、props</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#组合属性名称"><span class="toc-number">3.9.</span> <span class="toc-text">组合属性名称</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Spring的Bean和JavaBean"><span class="toc-number">3.10.</span> <span class="toc-text">Spring的Bean和JavaBean</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring_3-0提供的Java配置管理"><span class="toc-number">4.</span> <span class="toc-text">Spring 3.0提供的Java配置管理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Bean实例的创建方式及依赖配置"><span class="toc-number">5.</span> <span class="toc-text">Bean实例的创建方式及依赖配置</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#使用构造器创建Bean实例"><span class="toc-number">5.1.</span> <span class="toc-text">使用构造器创建Bean实例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用静态工厂方法创建Bean"><span class="toc-number">5.2.</span> <span class="toc-text">使用静态工厂方法创建Bean</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#调用实例工厂方法创建Bean"><span class="toc-number">5.3.</span> <span class="toc-text">调用实例工厂方法创建Bean</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#深入理解容器中的Bean"><span class="toc-number">6.</span> <span class="toc-text">深入理解容器中的Bean</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#使用抽象Bean"><span class="toc-number">6.1.</span> <span class="toc-text">使用抽象Bean</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用子Bean"><span class="toc-number">6.2.</span> <span class="toc-text">使用子Bean</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Bean继承与Java继承的区别"><span class="toc-number">6.3.</span> <span class="toc-text">Bean继承与Java继承的区别</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#容器中的_工厂Bean"><span class="toc-number">6.4.</span> <span class="toc-text">容器中的 工厂Bean</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#获得Bean部署时的id"><span class="toc-number">6.5.</span> <span class="toc-text">获得Bean部署时的id</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#强制初始化Bean"><span class="toc-number">6.6.</span> <span class="toc-text">强制初始化Bean</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#容器中Bean的生命周期"><span class="toc-number">7.</span> <span class="toc-text">容器中Bean的生命周期</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#依赖关系注入之后的行为"><span class="toc-number">7.1.</span> <span class="toc-text">依赖关系注入之后的行为</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Bean_销毁之前的行为"><span class="toc-number">7.2.</span> <span class="toc-text">Bean 销毁之前的行为</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#协调作用域不同步的Bean"><span class="toc-number">7.3.</span> <span class="toc-text">协调作用域不同步的Bean</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#深入理解依赖关系配置"><span class="toc-number">8.</span> <span class="toc-text">深入理解依赖关系配置</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#注入其他Bean的属性值"><span class="toc-number">8.1.</span> <span class="toc-text">注入其他Bean的属性值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#注入其他Bean的Field值"><span class="toc-number">8.2.</span> <span class="toc-text">注入其他Bean的Field值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#注入其他Bean的方法返回值"><span class="toc-number">8.3.</span> <span class="toc-text">注入其他Bean的方法返回值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#基于xml_schema_的简化配置方式"><span class="toc-number">9.</span> <span class="toc-text">基于xml schema 的简化配置方式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#使用p名称空间配置属性"><span class="toc-number">9.1.</span> <span class="toc-text">使用p名称空间配置属性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用util_Schema"><span class="toc-number">9.2.</span> <span class="toc-text">使用util Schema</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring3-0提供的表达式语言(SpEl)"><span class="toc-number">10.</span> <span class="toc-text">Spring3.0提供的表达式语言(SpEl)</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#使用Expression接口进行表达式求值"><span class="toc-number">10.1.</span> <span class="toc-text">使用Expression接口进行表达式求值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Bean定义中的表达式语言支持"><span class="toc-number">10.2.</span> <span class="toc-text">Bean定义中的表达式语言支持</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#SpEL语法详述"><span class="toc-number">10.3.</span> <span class="toc-text">SpEL语法详述</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#基本表达式"><span class="toc-number">10.3.1.</span> <span class="toc-text">基本表达式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#类相关表达式"><span class="toc-number">10.3.2.</span> <span class="toc-text">类相关表达式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#集合相关表达式"><span class="toc-number">10.3.3.</span> <span class="toc-text">集合相关表达式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#表达式模板"><span class="toc-number">10.3.4.</span> <span class="toc-text">表达式模板</span></a></li></ol></li></ol></li></ol>
		
		</div>
		
        <p>使用Spring框架，必须使用Spring Core Container，主要由<code>org.springframework.core</code>、<code>org.springframework.beans</code>和<code>org.springframework.context</code>、<code>org.springframework.expression</code>四个包及其子包组成，主要提供Spring IoC容器支持。</p>
<a id="more"></a>
<p><img src="http://fh-1.qiniudn.com/spring3-modules.png" alt="Spring组成结构" title="Spring组成结构"></p>
<h2 id="Spring核心机制：依赖注入">Spring核心机制：依赖注入</h2><p>Java应用（从applets的小范围到全套n层服务端企业应用）是一种典型的依赖型应用，它就是由一些互相适当地协作的对象构成的。因此，我们说这些对象间存在依赖关系。加入A组件调用了B组件的方法，我们就可以称A组件依赖于B组件。我们通过使用依赖注入，Java EE应用中的各种组件不需要以硬编码方式耦合在一起，甚至无需使用工厂模式。当某个Java 实例需要其他Java 实例时，系统自动提供所需要的实例，无需程序显示获取，这种自动提供java实例我们谓之为依赖注入，也可以称之为控制反转（Inversion of Control IoC）。</p>
<p>依赖注入通常有如下两种：</p>
<ol>
<li>设置注入：IoC容器使用属性的setter方法来注入被依赖的实例。</li>
<li>构造注入：IoC容器使用构造器来注入被依赖的实例。</li>
</ol>
<h3 id="设值注入">设值注入</h3><p>设值注入是指IoC容器使用属性的setter方法来注入被依赖的实例。这种注入方式比较简单、直观。<br>下面是Person接口，该接口定义了一个Person规范。</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public interface <span class="keyword">Person</span> &#123;</span><br><span class="line">    //定义使用斧子的方法</span><br><span class="line">    public void useAxe();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Axe接口：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title">Axe</span> &#123;</span><br><span class="line">    <span class="comment">//Axe接口里面有个砍的方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">chop</span>(<span class="params"></span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Person的实现类。</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">public class Chinese implements <span class="keyword">Person</span> &#123;</span><br><span class="line">    private Axe axe;</span><br><span class="line">    private String name;</span><br><span class="line"></span><br><span class="line">    // 设值注入所需的setter方法</span><br><span class="line">    public void setAxe(Axe axe) &#123;</span><br><span class="line">        this.axe = axe;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setName(String name) &#123;</span><br><span class="line">        this.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    // 实现<span class="keyword">Person</span>接口的userAxe方法</span><br><span class="line">    public void useAxe() &#123;</span><br><span class="line">        // 调用axe的chop方法，表明<span class="keyword">Person</span>对象依赖于Axe对象</span><br><span class="line">        System.out.println(<span class="string">"我是"</span>+name+<span class="string">"用"</span>+axe.chop());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的代码实现了Person接口的userAxe()方法，实现该方法时调用了axe的的chop()方法，这就是典型的依赖关系。</p>
<p>在这里Spring容器的作用就是已松耦合的方式来管理这种调用关系。在上面的Chinese类中，Chinese类并不知道它要调用的axe实例在哪里，也不知道axe实例是如何实现的，它只是需要调用一个axe实例，这个Axe实例将由Spring容器负责注入。<br>Axe的实现类：StoneAxe类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StoneAxe</span> <span class="keyword">implements</span> <span class="title">Axe</span></span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">chop</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"石斧砍柴好慢啊!!!"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>直到这里，程序依然不知道Chinese类和Axe实例耦合，Spring也不知道！实际上，Spring需要使用XML配置文件来指定实例之间的依赖关系。<br>Spring采用了XML文件作为配置文件。<br>对于本应用的XML配置文件如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">beans</span> <span class="attribute">xmlns:xsi</span>=<span class="value">"http://www.w3.org/2001/XMLSchema-instance"</span></span><br><span class="line"><span class="attribute">xmlns</span>=<span class="value">"http://www.springframework.org/schema/beans"</span></span><br><span class="line"><span class="attribute">xsi:schemaLocation</span>=<span class="value">"http://www.springframework.org/schema/beans</span><br><span class="line">http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 配置Chinese实例，其实现类是Chinese --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"chinese"</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.Chinese"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 将StoneAxe注入给axe属性 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"axe"</span> <span class="attribute">ref</span>=<span class="value">"stoneAxe"</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"name"</span> <span class="attribute">value</span>=<span class="value">"孙悟空"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 配置stoneAxe实例 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"stoneAxe"</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.StoneAxe"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>在配置文件中，Spring配置Bean实例通常会指定两个属性：</p>
<ul>
<li>id：指定该Bean的唯一标识，程序会通过id属性值来访问该Bean实例。</li>
<li>class：指定该Bean的实现类，此处不可再用接口，必须是实现类，Spring容器会使用XML解析器读取该属性值，并利用反射来创建该实现类的实例。</li>
</ul>
<p>从上面可以看出Bean于Bean之间的依赖关系放在配置文件里组织，而不是写在代码里。通过配置文件的指定，Spring能够精确地为每个Bean注入属性。因此，配置文件里的<code>&lt;bean…/&gt;</code>元素的class属性值不能是接口，而必须是真正的实现类。</p>
<p>Spring会自动接管每个<code>&lt;bean…/&gt;</code>定义里的<code>&lt;property …/&gt;</code>元素定义，Spring会在调用无参数的构造器、创建默认的Bean实例后，调用相应的setter方法为程序注入属性值。<code>&lt;property…/&gt;</code>定义的属性值将不再有该Bean来主动设置、管理，而是接受Spring的注入。</p>
<p>每个Bean的id属性是该Bean的唯一标识，程序通过id属性访问Bean，Bean与Bean的依赖关系也是通过id属性关联。<br>测试程序：</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">public class BeanTest &#123;</span><br><span class="line">    public static void main(String<span class="comment">[]</span> args) &#123;</span><br><span class="line">        //创建Spring容器</span><br><span class="line">        ApplicationContext ctx = new ClassPathXmlApplicationContext(<span class="string">"bean.xml"</span>);</span><br><span class="line">        //获取Chinese实例</span><br><span class="line">        <span class="keyword">Person</span> <span class="keyword">person</span> = ctx.getBean(<span class="string">"chinese"</span>,<span class="keyword">Person</span>.class);</span><br><span class="line">        <span class="keyword">person</span>.useAxe();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Bean与Bean之间的依赖关系有Spring管理，Spring采用setter方法为目标Be阿玛尼注入所依赖的Bean，这种方式被称之为设值注入。</p>
<p>从上面的实例我们可以看出，依赖注入以配置文件管理Bean实例之间的耦合，让Bean实例之间的耦合从代码层次分离出来。</p>
<p>Spring IoC容器有如下3个基本要点：</p>
<ol>
<li>应用程序的各个组件面向接口编程。面向接口编程可以将各个组件的耦合提升到接口层次，从而有利于项目后期的扩展。</li>
<li>应用程序的各组件不再由程序主动产生，而是由Spring容器来负责产生，并初始化。</li>
<li>Spring采用配置文件、或者Annotation来管理Bean的实现类、依赖关系，Spring容器则根据配置文件，利用反射机制来创建时间，并为之注入依赖关系。</li>
</ol>
<h3 id="构造注入">构造注入</h3><p>构造注入就是利用构造器来设置依赖关系的方式。<br>Japanese类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Chinese</span> <span class="keyword">implements</span> <span class="title">Person</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Axe axe;</span><br><span class="line">    <span class="comment">//默认构造器</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Chinese</span><span class="params">()</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//构造注入所需的带参数构造器</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Chinese</span><span class="params">(Axe axe)</span></span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.axe = axe;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">useAxe</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(axe.chop());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的Chinese类并没有setter方法，仅仅只是提供了一个带Axe属性的构造器，Spring将通过该构造器为Chinese注入所依赖的Bean实例。</p>
<p>构造注入的配置文件需要做一些修改。为了使用构造注入，使用<code>&lt;constructor-arg…/&gt;</code>元素来指定构造器的参数。如下</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">beans</span> <span class="attribute">xmlns:xsi</span>=<span class="value">"http://www.w3.org/2001/XMLSchema-instance"</span></span><br><span class="line"><span class="attribute">xmlns</span>=<span class="value">"http://www.springframework.org/schema/beans"</span></span><br><span class="line"><span class="attribute">xsi:schemaLocation</span>=<span class="value">"http://www.springframework.org/schema/beans</span><br><span class="line">http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 配置Chinese实例 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"chinese"</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.Chinese"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 使用构造注入，为Japanese实例注入SteelAxe实例--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">constructor-arg</span> <span class="attribute">ref</span>=<span class="value">"stoneAxe"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 配置stoneAxe实例 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"stoneAxe"</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.StoneAxe"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>上面的配置文件使用<code>&lt;contructor-arg…/&gt;</code>元素指定了一个构造器参数，该参数类型是Axe，这指定Spring调用Chinese类里带一个Axe参数的构造器来创建chinese实例，因为使用了有参数的构造器创建实例，所以当Bean实例被创建完成后，该Bean的依赖关系也就已经设置完成。</p>
<h3 id="两种注入方式的对比">两种注入方式的对比</h3><p>Spring支持两种依赖注入方式，这两种依赖注入方式并没有好坏之分，只是适合的场景有所不同。<br>设值注入有如下优点：</p>
<ol>
<li>与传统的JavaBean的写法更相似，程序开发人员更加容易理解，接受。通过setter方法设定依赖关系显得更加直观、自然。</li>
<li>对于复杂的依赖关系，如果采用构造注入，会导致构造器过于臃肿，难以阅读。Spring在创建Bean实例时，需要同时实例化其依赖的全部实例，因此导致性能下降。而设值注入，则可以避免这些问题。</li>
<li>尤其是在某些属性可选的情况下，多参数的构造器更加笨重。</li>
</ol>
<p>但是构造器也有如下优势：</p>
<ol>
<li>构造注入可以再构造器中决定依赖关系的注入顺序，优先依赖的优先注入。</li>
<li>对于依赖关系无须变化的Bean，构造注入更有用处。因为没有setter方法，所有的依赖关系全部在构造器中设定，因此，无须担心后续的代码对依赖关系产生破坏。</li>
<li>依赖关系只能在构造器中设定，则只有组件的创建者才能改变组件的依赖关系。对组件的调用者而言，组件内部的依赖关系完全透明，更加符合高内聚的原则。</li>
</ol>
<p>通过上面的对比。所以建议用以设值注入为主，构造注入为辅的注入策略。对于依赖关系无须变化的注入，尽量采用构造注入；而其他的依赖关系，则考虑设值注入。</p>
<p>Spring有两个核心接口：BeanFactory和ApplicationContext，其中ApplicationContext是BeanFactory的子接口。他们都可代表Spring容器，Spring容器是生成Bean实例的工厂，并且管理容器中的Bean。Bean是Spring管理的基本单位，在基于Spring的Java EE应用中，所有的组件都被当成Bean处理，包括数据源、Hibernate的SessionFactory、事务管理器等。</p>
<p>而且应用中的所有组件，都处于Spring的管理下，都被Spring以Bean的方式管理，Spring负责创建Bean实例，并管理他们的生命周期。Bean在Spring容器中运行，无须感受Spring容器的存在，一样可以接受Spring的依赖注入，包括Bean属性的注入，协作者的注入、依赖关系的注入等。</p>
<p>Spring容器负责创建Bean实例，所以需要知道每个Bean的实现类，Java程序面向接口编程，无须关心Bean实例的实现类；但是Spring容器必须能够精确知道每个Bean实例的实现类，因此Spring配置文件必须精确配置Bean实例的实现类。</p>
<h2 id="Spring容器">Spring容器</h2><p>Spring容器最基本的接口就是BeanFactory。BeanFactory负责配置、创建、管理Bean，他有一个子接口：ApplicationContext，因此也称之为Spring上下文。Spring容器负责管理Bean与Bean之间的依赖关系。</p>
<p>BeanFactory接口包含以下几个基本方法：</p>
<ul>
<li><code>Boolean containBean(String name)</code>:判断Spring容器是否包含id为name的Bean实例。</li>
<li><code>&lt;T&gt; getBean(Class&lt;T&gt; requiredTypr)</code>:获取Spring容器中属于requiredType类型的唯一的Bean实例。</li>
<li><code>Object getBean(String name)</code>：返回Sprin容器中id为name的Bean实例。</li>
<li><code>&lt;T&gt; T getBean(String name,Class requiredType)</code>：返回容器中id为name,并且类型为requiredType的Bean</li>
<li><code>Class &lt;?&gt; getType(String name)</code>：返回容器中指定Bean实例的类型。</li>
</ul>
<p>在使用BeanFactory接口时，我们一般都是使用这个实现类：org.springframework.beans.factory.xml.XmlBeanFactory。然而ApplicationContext作为BeanFactory的子接口，使用它作为Spring容器会更加方便。它的实现类有：FileSystemXmlApplicationContext、ClassPathXmlApplicationContext、AnnotationConfigApplicationContext。</p>
<p>创建Spring容器实例时，必须提供Spring容器管理的Bean的详细配置信息。Spring的配置信息通常采用xml配置文件来设置，因此，创建BeanFactory实例时，应该提供XML配置文件作为参数。</p>
<p>XML配置文件通常使用Resource对象传入。Resource接口是Spring提供的资源访问接口，通过使用该接口，Spring能够以简单、透明的方式访问磁盘、类路径以及网络上的资源。</p>
<p>对于Java EE应用而言，可在启动Web应用时自动加载ApplicationContext实例，接受Spring管理的Bean无须知道ApplicationContext的存在。一般使用如下方式实例化BeanFactory</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//搜索当前文件路径下的bean.xml文件创建Resource对象</span></span><br><span class="line">InputStreamSource isr = <span class="keyword">new</span> FileSystemResource(<span class="string">"bean.xml"</span>);</span><br><span class="line"><span class="comment">//以Resource对象作为参数创建BeanFactory实例</span></span><br><span class="line">XmlBeanFactory <span class="literal">factory</span> = <span class="keyword">new</span> XmlBeanFactory((Resource) isr);</span><br></pre></td></tr></table></figure>
<p>或</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ClassPathResource res = <span class="keyword">new</span> ClassPathResource(<span class="string">"bean.xml"</span>);</span><br><span class="line"><span class="comment">//以Resource对象作为参数创建BeanFactory实例</span></span><br><span class="line">XmlBeanFactory <span class="literal">factory</span> = <span class="keyword">new</span> XmlBeanFactory(res);</span><br></pre></td></tr></table></figure>
<p>但是如果应用里面有多个属性配置文件，则应该采用BeanFactory的子接口ApplicationContext来创建BeanFactory的实例。ApplicationContext通常使用如下两个实现类：</p>
<ul>
<li>FileSystemXmlApplicationContext：以基于文件系统的XML配置文件创建ApplicationContext实例。</li>
<li>ClassPathXmlApplicationContext：以类加载路径下的XML配置文件创建的ApplicationContext实例。<br>如果需要同时加载多个XML配置文件，采用如下方式：</li>
</ul>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//搜索CLASSPATH路径，以classpath路径下的bean.xml、service.xml文件创建applicationContext</span></span><br><span class="line">ApplicationContext ctx = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="keyword">new</span> <span class="built_in">String</span>[]&#123;<span class="string">"bean.xml"</span>,<span class="string">"service.xml"</span>&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//以指定路径下的bean.xml、service.xml文件创建applicationContext</span></span><br><span class="line">ApplicationContext ctx1 = <span class="keyword">new</span> FileSystemXmlApplicationContext(<span class="keyword">new</span> <span class="built_in">String</span>[]&#123;<span class="string">"bean.xml"</span>,<span class="string">"service.xml"</span>&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="使用ApplicationContext">使用ApplicationContext</h3><p>ApplicationContext允许以声明式方式操作容器，无须手动创建它。在Web应用启动时自动创建ApplicationContext。当然，也可以采用编程方式创建ApplicationContext。</p>
<p>除了提供BeanFactory所支持的全部功能外，ApplicationContext还有如下功能：</p>
<ol>
<li>ApplicationContext继承MessageSource接口，因此提供国际化支持。</li>
<li>资源访问。</li>
<li>事件机制。</li>
<li>载入多个配置文件。</li>
<li>以声明式的方式启动，并创建Spring容器。</li>
</ol>
<p>当系统创建ApplicationContext容器时，默认会预初始化所有的singleton Bean。也就是说，当ApplicationContext容器初始化完成后，容器中所有singleton Bean也实例化完成，这就意味着：系统前期创建ApplicationContext时将有较大的系统开销，但一旦ApplicationContext初始化完成，程序后面获取singleton Bean实例时将拥有较好的性能。</p>
<h3 id="ApplicationContext的国际化支持">ApplicationContext的国际化支持</h3><p>ApplicationContext接口继承MessageSource接口，因此具备国际化功能。MessageSource接口中定义了三个方法用于国际化功能。</p>
<ul>
<li><code>String getMessage(String code,Object[] args,Locale loc);</code></li>
<li><code>String getMessage(String code,Object[] args,String default,Locale loc);</code></li>
<li><code>String getMessage(MessageSourceResolvable resolvable,Local loc);</code></li>
</ul>
<p>ApplicationContext正是通过这三个方法来实现国际化的。当程序创建ApplicationContext容器时，Spring会自动查找在配置文件中名为messageSource的bean实例，一旦找到这个Bean实例，上述三个方法的调用被委托给该MessageSource Bean。如果没有该Bean，ApplicationContext会查找其父定义中的messagesource Bean，如果找到，它会作为messageSource Bean使用。但是如果无法找到messageSource，系统将会创建一个空的staticMessageSource Bean，该Bean的能接受上述三个方法的调用。</p>
<p>在Spring中配置messagesourceBean时通常使用ResourceBundleMessageSource.如下：<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">beans</span> <span class="attribute">xmlns:xsi</span>=<span class="value">"http://www.w3.org/2001/XMLSchema-instance"</span></span><br><span class="line"><span class="attribute">xmlns</span>=<span class="value">"http://www.springframework.org/schema/beans"</span></span><br><span class="line"><span class="attribute">xsi:schemaLocation</span>=<span class="value">"http://www.springframework.org/schema/beans</span><br><span class="line">http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"messsageSource"</span> <span class="attribute">class</span>=<span class="value">"org.springframework.context.support.ResourceBundleMessageSource"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"basenames"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">list</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">value</span>&gt;</span>message<span class="tag">&lt;/<span class="title">value</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--如果有多个资源文件，全部列在此处--&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">list</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">beans</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>message.properties:<br><figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="setting">hello=<span class="value">欢迎你:&#123;<span class="number">0</span>&#125;</span></span></span><br><span class="line"><span class="setting">now=<span class="value">现在时间是:&#123;<span class="number">0</span>&#125;</span></span></span><br></pre></td></tr></table></figure></p>
<p>配置文件中包含非西欧文字需要使用native2ascii工具<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">native2ascii</span> <span class="tag">message</span><span class="class">.properties</span> <span class="tag">message_zh_CN</span><span class="class">.properties</span></span><br></pre></td></tr></table></figure></p>
<p>使用<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">ApplicationContext ctx = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">"bean.xml"</span>);</span><br><span class="line"><span class="built_in">String</span>[] a =&#123;<span class="string">"howie"</span>&#125;;</span><br><span class="line"><span class="built_in">String</span> hello = ctx.getMessage(<span class="string">"hello"</span>,a, Locale.getDefault());</span><br><span class="line"><span class="built_in">Object</span>[] b = &#123;<span class="keyword">new</span> <span class="built_in">Date</span>()&#125;;</span><br><span class="line"><span class="built_in">String</span> now = ctx.getMessage(<span class="string">"now"</span>,b,Locale.getDefault());</span><br></pre></td></tr></table></figure></p>
<h3 id="ApplicationContext的事件机制">ApplicationContext的事件机制</h3><p>ApplicationContext的事件机制是观察者设计模式的实现，通过ApplicationEvent类和ApplicationListener接口，可以实现ApplicationContext的事件处理。</p>
<p>Spring的事件框架有如下两个重要成员：</p>
<ol>
<li>ApplicationEvent：容器事件，必须由ApplicationContext发布。</li>
<li>ApplicationListener：监听器，可由容器中的任何监听器Bean担任。</li>
</ol>
<p>Spring的事件机制需要事件源、事件和事件监听器组成。只是此处的事件是ApplicationContext，且事件必须由java程序显示触发。下图简单示范了ApplicationContext的事件流程。</p>
<p>下面实例展示了Spring容器的事件机制。</p>
<ol>
<li><p>定义一个ApplicationEvent类，其对象就是Spring容器事件。</p>
 <figure class="highlight processing"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> class EmailEvent extends ApplicationEvent &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">1</span>L;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">String</span> address;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">String</span> <span class="built_in">text</span>;</span><br><span class="line">    <span class="comment">// 定义一个带参的构造函数</span></span><br><span class="line">    <span class="keyword">public</span> EmailEvent(<span class="keyword">Object</span> source) &#123;</span><br><span class="line">        <span class="keyword">super</span>(source);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> EmailEvent(<span class="keyword">Object</span> source, <span class="keyword">String</span> address, <span class="keyword">String</span> <span class="built_in">text</span>) &#123;</span><br><span class="line">        <span class="keyword">super</span>(source);</span><br><span class="line">        <span class="keyword">this</span>.address = address;</span><br><span class="line">        <span class="keyword">this</span>.<span class="built_in">text</span> = <span class="built_in">text</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//address、text的setter和getter方法</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p> 容器事件的监听器类必须实现ApplicationListener接口，它的实现方法如下：<br> onAPplicationEvent(ApplicationEventevent):每当容器内发生任何事件时，此方法都会被触发。</p>
</li>
<li><p>编写该容器的监听器类。</p>
 <figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">EmailNotifier</span> <span class="title">implements</span> <span class="title">ApplicationListener</span>&#123;</span><br><span class="line">    <span class="comment">//该方法会在容器发生事件时触发</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onApplicationEvent</span>(<span class="params">ApplicationEvent <span class="keyword">event</span></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(<span class="keyword">event</span> instanceof EmailEvent)&#123;</span><br><span class="line">            <span class="comment">//只处理EmailEvent，发送email通知</span></span><br><span class="line">            EmailEvent emailEvent = (EmailEvent) <span class="keyword">event</span>;</span><br><span class="line">            System.<span class="keyword">out</span>.println(<span class="string">"需要发送邮件的接收地址为:"</span>+emailEvent.getAddress());</span><br><span class="line"></span><br><span class="line">            System.<span class="keyword">out</span>.println(<span class="string">"需要发送邮件的邮件正文是:"</span>+emailEvent.getText());</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">//容器内置事件不作任何处理</span></span><br><span class="line">            System.<span class="keyword">out</span>.println(<span class="string">"容器本身的事件:"</span>+<span class="keyword">event</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>将监听器类配置在容器中。</p>
<p> 在为Spring容器注册监听器时，我们只需在Spring配置文件中配置一个实现了ApplicationListener的Bean即可，Spring容器会把这个Bean当做容器事件的监听器。</p>
 <figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">beans</span> <span class="attribute">xmlns:xsi</span>=<span class="value">"http://www.w3.org/2001/XMLSchema-instance"</span></span><br><span class="line"><span class="attribute">xmlns</span>=<span class="value">"http://www.springframework.org/schema/beans"</span></span><br><span class="line"><span class="attribute">xsi:schemaLocation</span>=<span class="value">"http://www.springframework.org/schema/beans</span><br><span class="line">http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 配置监听器 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">class</span>=<span class="value">"com.app.listener.EmailNotifier"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>通过上面的3个步骤就可以实现Spring容器的事件了。当系统创建Spring容器，加载Spring容器时会自动触发容器事件，容器事件监听器可以监听到这些事件。同时我们也可以调用ApplicationContext的pulishEvent()方法来主动触发容器事件。</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">SpringTest</span> &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span>(<span class="params">String[] args</span>) </span>&#123;</span><br><span class="line">        ApplicationContext ctx = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">"bean.xml"</span>);</span><br><span class="line">        <span class="comment">//创建一个ApplicationEvent对象</span></span><br><span class="line">        EmailEvent emailEvent = <span class="keyword">new</span> EmailEvent(<span class="string">"hello"</span>,<span class="string">"spring_test@163.com"</span>,<span class="string">"this is a test"</span>);</span><br><span class="line">        <span class="comment">//主动触发容器事件</span></span><br><span class="line">        ctx.publishEvent(emailEvent);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果Bean想发布事件，则Bean必须获得其容器的引用。如果程序中没有直接获取容器的引用，则应该让Bean实现ApplicationContextAware或BeanFactoryAware接口，从而获得容器的引用。</p>
<p>除了我们可以自己实现Spring容器的事件外，Spring也提供了几个内置事件：</p>
<ol>
<li>ContextRefreshedEvent：ApplicationContext容器初始化或者刷新时触发该事件。</li>
<li>ContextStartedEvent：当使用ConfigurableApplicationContext接口的start()方法启动ApplicationContext容器时触发该事件。</li>
<li>ContextClosedEvent：当使用ConfigurableApplicationContext接口的close()方法关闭ApplicationContext容器时触发该事件。</li>
<li>ContextStopedEvent: 当使用ConfigurableApplicationContext接口的stop()方法停止ApplicationContext容器时触发该事件。</li>
</ol>
<h3 id="让Bean获取Spring容器">让Bean获取Spring容器</h3><p>在Spring中我们可以使用Spring容器中getBean()方法来获取Spring容器中的Bean实例。在这样的访问模式下，程序中总是持有Spring容器的引用。但是在实际的应用中，Spring容器通常是采用声明式方式配置产生：即开发者只要在web.xml文件中配置一个Listener，该Listener将会负责初始化Spring容器。在这种情况下，容器中Bean处于容器管理下，无须主动访问容器，只需要接受容器的注入管理即可。同时Bean实例的依赖关系通常也是由容器动态注入，无须Bean实例主动请求。</p>
<p>在这种情况下，Sprig容器中Bean通常不会需要访问容器中其他的Bean—采用依赖注入，让Spring把被依赖的Bean注入到依赖的Bean中即可。</p>
<p>实现BeanFactoryAware接口的Bean，拥有访问的BeanFactory容器的能力，实现BeanFactoryAware接口的Bean实例将会拥有对容器的访问能力。BeanFactoryAware接口仅有如下一个方法：</p>
<p>setBeanFactory(BeanFactory beanFactory)：该方法有一个参数beanFactory，该参数指向创建它的BeanFactory。</p>
<p>该方法将由Spring调动，当Spring调用该方法时会将Spring容器作为参数传入该方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Chinese</span> <span class="keyword">implements</span> <span class="title">ApplicationContextAware</span></span>&#123;</span><br><span class="line">    <span class="comment">//将BeanFactory容器以成员变量保存</span></span><br><span class="line">    <span class="keyword">private</span> ApplicationContext ctx;</span><br><span class="line">    <span class="comment">/**</span><br><span class="line">     * 实现ApplicationContextAware接口实现的方法</span><br><span class="line">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setApplicationContext</span><span class="params">(ApplicationContext cyx)</span>  <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.ctx = ctx;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//获取ApplicationContext的测试方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ApplicationContext <span class="title">getContext</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> ctx;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的Chinese类实现了ApplicationContext接口，并实现了该接口提供的setApplicationContextAware()方法，这就使得该Bean实例可以直接访问到创建她的Spring容器。<br>将该Bean部署在Spring容器中。<br>测试类：<br>该程序先通过实例化的方法来获取ApplicationContext，然后通过chinese Bean来获得BeanFactory，并将两者进行比较。</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">ChineseTest</span> &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span>(<span class="params">String[] args</span>) </span>&#123;</span><br><span class="line">        ApplicationContext ctx = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">"bean.xml"</span>);</span><br><span class="line">        Chinese c = ctx.getBean(<span class="string">"chinese"</span>,Chinese.class);</span><br><span class="line">        System.<span class="keyword">out</span>.println(c.getContext());</span><br><span class="line">        System.<span class="keyword">out</span>.println(c.getContext()==ctx);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//结果如下：</span></span><br><span class="line"><span class="keyword">true</span></span><br></pre></td></tr></table></figure>
<p>上面的代码虽然实现了ApplicationContextAware接口让Bean拥有了访问容器的能力，但是污染了代码，导致代码与Spring接口耦合在一起。所以，如果不是特别需要，一般不建议直接访问容器。</p>
<h2 id="Spring容器中的Bean">Spring容器中的Bean</h2><p>从前面我们知道Spring其实就是一个大型的工厂，而Spring容器中的Bean就是该工厂的产品.对于Spring容器能够生产那些产品，则取决于配置文件中配置。</p>
<p>对于我们而言，我们使用Spring框架所做的就是两件事：开发Bean、配置Bean。对于Spring框架来说，它要做的就是根据配置文件来创建Bean实例，并调用Bean实例的方法完成“依赖注入”。</p>
<h3 id="Bean的基本定义">Bean的基本定义</h3><p>beans元素可以有以下属性，bean元素可以有没有default-前缀的属性，beans属性是全局的。</p>
<ul>
<li>default-lazy-init ：延迟初始化</li>
<li>default-merge：merge行为</li>
<li>default-autowire：自动装配行为</li>
<li>default-autowire-candidates：自动装配候选bean</li>
<li>default-init-method：初始化方法</li>
<li>default-destroy-method：回收方法</li>
</ul>
<p><code>&lt;beans…/&gt;</code>元素是Spring配置文件的根元素，<code>&lt;bean…/&gt;</code>元素师<code>&lt;beans../&gt;</code>元素的子元素，<code>&lt;beans…/&gt;</code>元素可以包含多个<code>&lt;bean…/&gt;</code>子元素，每个<code>&lt;bean…/&gt;</code>元素可以定义一个Bean实例，每一个Bean对应Spring容器里的一个Java实例定义Bean时通常需要指定两个属性。</p>
<ul>
<li>id：确定该Bean的唯一标识符，容器对Bean管理、访问、以及该Bean的依赖关系，都通过该属性完成。Bean的id属性在Spring容器中是唯一的。</li>
<li>class：指定该Bean的具体实现类。注意这里不能是接口。通常情况下，Spring会直接使用new关键字创建该Bean的实例，因此，这里必须提供Bean实现类的类名。</li>
</ul>
<p>下面是定义一个Bean的简单配置<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 定义第一个Bean实例：bean1 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"bean1"</span> <span class="attribute">class</span>=<span class="value">"com.Bean1"</span> /&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 定义第二个Bean实例：bean2 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"bean2"</span> <span class="attribute">class</span>=<span class="value">"com.Bean2"</span> /&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>当我们在配置文件中通过<code>&lt;bean id=”xxx” class=”x.xxxClass”/&gt;</code>方法配置一个Bean时，这样就需要该Bean实现类中必须有一个无参构造器。故Spring底层相当于调用了如下代码：<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">xxx = new x.<span class="function"><span class="title">xxxClass</span><span class="params">()</span></span></span><br></pre></td></tr></table></figure></p>
<p>如果在配置文件中通过构造注入来创建Bean：<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"bean1"</span> <span class="attribute">class</span>=<span class="value">"com.Bean1"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">constructor-arg</span> <span class="attribute">value</span>=<span class="value">"chenssy"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">constructor-arg</span> <span class="attribute">value</span>=<span class="value">"35-354"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>则Spring相当于调用如下代码：<br><figure class="highlight armasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">Bean </span><span class="keyword">bean </span>= new com.Test(<span class="string">"chenssy"</span>,<span class="string">"35-354"</span>)<span class="comment">;</span></span><br></pre></td></tr></table></figure></p>
<p>除了可以为<code>&lt;bean…/&gt;</code>元素指定一个id属性外，还可以为<code>&lt;bean…/&gt;</code>元素指定name属性，用于为Bean实例指定别名。如果需要为Bean实例指定多个别名，可以在name属性中使用逗号、冒号或者空格来分隔多个别名，后面通过任一别名即可访问该Bean实例。但是在一些特殊的情况下，程序无法在定义Bean时就指定所有的别名，而是在其他地方为一个已经存在的Bean实例指定别名，则可以使用<code>&lt;alias…/&gt;</code>元素来完成，该元素有如下两个属性：</p>
<ul>
<li>name：该属性指定一个Bean实例的标识名，表示将会为该Bean指定别名。</li>
<li>alias：指定一个别名.<br>如：</li>
</ul>
<figure class="highlight monkey"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;<span class="keyword">alias</span> <span class="title">name</span>=”bean1” <span class="keyword">alias</span>=”name1”/&gt;</span><br><span class="line">&lt;<span class="keyword">alias</span> <span class="title">name</span>=”bean2” <span class="keyword">alias</span>=”name2”/&gt;</span><br></pre></td></tr></table></figure>
<p>在默认情况下，当Spring创建ApplicationContext容器时，Spring会自动预初始化容器中所有的singleton实例，如果我们想让Spring容器预初始化某个singleton Bean，则可以为该<code>&lt;bean…/&gt;</code>元素增加lazy-init属性，该属性用于指定该Bean实例的预初始化，如果设置为true，则Spring不会预初始化该Bean实例。</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=”<span class="keyword">person</span>” class=”com.<span class="keyword">Person</span>” lazy-init=”true”/&gt;</span><br></pre></td></tr></table></figure>
<h3 id="容器中Bean的作用域">容器中Bean的作用域</h3><p>当通过Spring容器创建一个Bean实例时，不仅可以完成Bean实例的实例化，还可以为Bean指定特定的作用域。Spring支持5种作用域：</p>
<ul>
<li>singleton：单例模式。在整个Spring IoC容器中，使用singleton定义的Bean将只有一个实例。</li>
<li>prototype：原型模式。每次通过容器的getBean方法获取prototype定义的Bean时，都将产生一个新的Bean实例。</li>
<li>request：对于每次HTTP请求，使用request定义的Bean都将产生一个新的实例，即每次HTTP请求都会产生不同的Bean实例。当然只有在WEB应用中使用Spring时，该作用域才真正有效。</li>
<li>session：对于每次HTTPSession，使用session定义的Bean都将产生一个新的实例时，即每次HTTP Session都将产生不同的Bean实例。同HTTP一样，只有在WEB应用才会有效。</li>
<li>global session：每个全局的HTTPSession对应一个Bean实例。仅在portlet Context的时候才有效。</li>
</ul>
<p>比较常用的singleton和prototype。如果一个Bean实例被设置为singleton，那么每次请求该Bean时都会获得相同的实例。容器负责跟踪Bean实例的状态，负责维护Bean实例的生命周期行为。如果一个Bean实例被设置为prototype，那么每次请求该id的Bean，Spring都会创建一个新的Bean实例返回给程序，在这种情况下，Spring容器仅仅使用new关键字创建Bean实例，一旦创建成功，容器将不会再跟踪实例，也不会维护Bean实例的状态。<strong>Spring默认使用singleton作用域</strong>。prototype作用域Bean的创建、销毁代价会比较大。除非必要，否则尽量避免将Bean的作用域设置为prototype。</p>
<p>设置Bean的作用域是通过scope属性来指定。可以接受singleton、prototype、request、session、global session 5个值。<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 配置一个singleton Bean实例：默认 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"bean1"</span> <span class="attribute">class</span>=<span class="value">"com.Bean1"</span> /&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 配置一个prototype Bean实例 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"bean2"</span> <span class="attribute">class</span>=<span class="value">"com.Bean2"</span> <span class="attribute">scope</span>=<span class="value">"prototype"</span>/&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>测试代码：<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">SpringTest</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span>(<span class="params">String[] args</span>) </span>&#123;</span><br><span class="line">        ApplicationContext ctx = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">"bean.xml"</span>);</span><br><span class="line">        <span class="comment">//判断两次请求singleton作用域的Bean实例是否相等</span></span><br><span class="line">        System.<span class="keyword">out</span>.println(ctx.getBean(<span class="string">"bean1"</span>)==ctx.getBean(<span class="string">"bean1"</span>));</span><br><span class="line">        <span class="comment">//判断两次请求prototype作用域的Bean实例是否相等</span></span><br><span class="line">        System.<span class="keyword">out</span>.println(ctx.getBean(<span class="string">"bean2"</span>)==ctx.getBean(<span class="string">"bean2"</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//程序运行结果如下</span></span><br><span class="line"><span class="keyword">true</span></span><br><span class="line"><span class="keyword">false</span></span><br></pre></td></tr></table></figure></p>
<p>request和session作用域只在web应用中才会有效，并且必须在Web应用中增加额外配置才会生效。为了能够让request和session两个作用域生效，必须将HTTP请求对象绑定到位该请求提供的服务线程上，这使得具有request和session作用的Bean实例能够在后面的调用链中被访问到。</p>
<p>因此我们可以采用两种配置方式：采用Listener配置或者采用Filter配置，在web.xml中。<br>Listener配置：<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;listener&gt;</span><br><span class="line">&lt;listener-class&gt;</span><br><span class="line">org<span class="class">.springframework</span><span class="class">.web</span><span class="class">.context</span><span class="class">.request</span><span class="class">.RequestContextListener</span></span><br><span class="line">&lt;/listener-class&gt;</span><br><span class="line">&lt;/listener&gt;</span><br></pre></td></tr></table></figure></p>
<p>Filter配置<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;<span class="attribute">filter</span>&gt;</span><br><span class="line">&lt;<span class="attribute">filter</span>-name&gt;requestContextFilter&lt;/<span class="attribute">filter</span>-name&gt;</span><br><span class="line">&lt;<span class="attribute">filter</span>-class&gt;org<span class="class">.springframework</span><span class="class">.web</span><span class="class">.filter</span><span class="class">.RequestContextFilter</span>&lt;/<span class="attribute">filter</span>-class&gt;</span><br><span class="line">&lt;/<span class="attribute">filter</span>&gt;</span><br><span class="line">&lt;<span class="attribute">filter</span>-mapping&gt;</span><br><span class="line">&lt;<span class="attribute">filter</span>-name&gt;requestContextFilter&lt;/<span class="attribute">filter</span>-name&gt;</span><br><span class="line">&lt;url-pattern&gt;<span class="comment">/*&lt;/url-pattern&gt;</span><br><span class="line">&lt;/filter-mapping&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>一旦在web.xml中增加上面两种配置中的一种，程序就可以在Spring配置文件中使用request或者session作用域了。如下：<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 指定使用request作用域 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"p"</span> <span class="attribute">class</span>=<span class="value">"com.app.Person"</span> <span class="attribute">scope</span>=<span class="value">"request"</span>/&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>上面的配置文件配置了一个实现类Person的Bean，指定它的作用域为request。这样Spring容器会为每次的HttP请求生成一个Person的实例，当该请求响应结束时，该实例也会被注销。</p>
<h3 id="配置依赖">配置依赖</h3><p>在一般情况下，我是不应该在配置文件中管理普通属性的引用，通常只是用配置文件管理容器中的Bean实例的依赖关系。</p>
<p>Spring在实例化容器时，会校验BeanFactory中每一个Bean的配置。这些校验包括：</p>
<ul>
<li>Bean引用的依赖Bean是否指向一个合法的Bean。</li>
<li>Bean的普通属性值是否获得一个有效值。</li>
</ul>
<p>对于singleton作用域的Bean，如果没有强行取消其预初始化的行为，系统会在创建Spring容器时预初始化所用singleton Bean，与此同时，该Bean所依赖的Bean也被一起实例化。</p>
<p>BeanFactory与ApplicationContext实例化容器中的Bean的时机也是不同的：BeanFactory等到程序需要Bean实例时才创建Bean，而ApplicationContext是在创建ApplicationContext实例时，会预初始化容器中的全部Bean。</p>
<p>ApplicationContext实例化过程比BeanFactory实例化过程的时间和内存开销大，但是一旦创建成功，应用后面的响应速度会非常快，同时可以检验出配置错误，故一般都是推荐使用ApplicationContext作为Spring容器。</p>
<p>其实我们可以指定lazy-int=”true”来强制取消singleton作用域的Bean的预初始。这样该Bean就不会随着ApplicationContext启动而预实例化了。</p>
<p>Spring可以为任何java对象注入任何类型的属性，只要改java对象为该属性提供了对应的setter方法即可。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"person"</span> <span class="attribute">class</span>=<span class="value">"lee.Person"</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- Property配置需要依赖注入的属性 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"name"</span> <span class="attribute">value</span>=<span class="value">"chenming"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"age"</span> <span class="attribute">value</span>=<span class="value">"22"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>Spring会为<code>&lt;bean…/&gt;</code>元素创建一个java对象，一个这样的java对象对应一个Bean实例，对于如上代码，Spring会采用如下形式来创建Java实例。</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">//获取lee.<span class="keyword">Person</span>类的Class对象</span><br><span class="line">Class  personClass = Class.forName(<span class="string">"lee.Person"</span>);</span><br><span class="line">//创建lee.<span class="keyword">Person</span>类的默认实例</span><br><span class="line">Object personBean = personBean.newInStance();</span><br></pre></td></tr></table></figure>
<p>创建该实例后，Spring就会遍历该<code>&lt;bean../&gt;</code>元素的所有<code>&lt;property…/&gt;</code>子元素。<code>&lt;bean…/&gt;</code>元素每包含一个<code>&lt;property…/&gt;</code>子元素，Spring就会为该Bean实例调用一次setter方法。类似于下面程序：</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">//获取name属性的setter方法</span><br><span class="line">String setName = <span class="string">"set"</span>+<span class="string">"Name"</span>;</span><br><span class="line">//获取lee.<span class="keyword">Person</span>类里面的Set()Name方法</span><br><span class="line">java.lang.reflect.Method setMethod = personClass.getMethod(setName, aVal.getClass());</span><br><span class="line">//调用Bean实例的SetName()方法</span><br><span class="line">setMethod.invoke(personBean, aVal);</span><br></pre></td></tr></table></figure>
<p>对于使用<code>&lt;constructor-arg…/&gt;</code>元素来指定构造器注入，Spring不会采用默认的构造器来创建Bean实例，而是使用特定的构造器来创建该Bean实例。<br><figure class="highlight nix"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean <span class="variable">id=</span><span class="string">"person"</span> <span class="variable">class=</span><span class="string">"lee.Person"</span>&gt;</span><br><span class="line">&lt;constructor-arg <span class="variable">index=</span><span class="string">"0"</span> <span class="variable">value=</span><span class="string">"aVal"</span> /&gt;</span><br><span class="line">&lt;constructor-arg <span class="variable">index=</span><span class="string">"1"</span> <span class="variable">value=</span><span class="string">"bVal"</span> /&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure></p>
<p>针对上面的代码，Spring会采用类似如下的代码来创建Bean实例：<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">//获取lee.<span class="keyword">Person</span>类的class对象</span><br><span class="line">Class  personClass = Class.forName(<span class="string">"lee.Person"</span>);</span><br><span class="line">//获取第一个参数是aVal类型，第二个参数是bVal类型的构造器</span><br><span class="line">Constructor personCtr = personClass.getConstructor(aVal.getClass(),bVal.getClass());</span><br><span class="line">//以指定构造器创建Bean实例</span><br><span class="line">Object bean = personCtr.newInstance(aVal,bVal);</span><br></pre></td></tr></table></figure></p>
<p>上面的程序只是一个实例，实际上Spring还需要根据<code>&lt;property…/&gt;</code>元素、<code>&lt;contructor-arg../&gt;</code>元素所使用value属性，ref属性等来判断需要注入的到底是什么数据类型，并要对这些值进行合适的类型转换，所以Spring的实际处理过程会更加复杂。</p>
<p>Java实例的属性值可以有很多种数据类型、基本类型值、字符串类型、java实例甚至其他的Bean实例、java集合、数组等。所以Spring允许通过如下几个元素为Bean实例的属性指定值：</p>
<ul>
<li>value</li>
<li>ref</li>
<li>bean</li>
<li>list、set、map、props</li>
</ul>
<h3 id="设置普通属性值">设置普通属性值</h3><p>value属性用于指定字符串类型、基本类型的属性值。Spring使用XML解析器来解析出这些数据，然后利用java.beans.PropertyEdior完成类型转换：从java.lang.String类型转换为所需的参数值类型。如果目标类型是基本数据类型，通常都是可以正确转换。<br><figure class="highlight axapta"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ValueTest</span> </span>&#123;</span><br><span class="line"><span class="comment">//定义一个String型属性</span></span><br><span class="line"><span class="keyword">private</span> String name;</span><br><span class="line"><span class="comment">//定义一个int型属性</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">int</span> age;</span><br><span class="line"><span class="comment">// name 、age的getter和setter方法</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面实例只是演示了注入普通属性值。在Spring配置文件中使用value属性来为这两个属性指定属性值。</p>
<figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean <span class="property">id</span>=<span class="string">"text"</span> <span class="type">class</span>=<span class="string">"com.spring.service.impl.ValueTest"</span>&gt;</span><br><span class="line">&lt;<span class="keyword">property</span> <span class="property">name</span>=<span class="string">"age"</span> value=<span class="string">"1"</span> /&gt;</span><br><span class="line">&lt;<span class="keyword">property</span> <span class="property">name</span>=<span class="string">"name"</span> value=<span class="string">"chenssy"</span> /&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure>
<h3 id="配置合作者">配置合作者</h3><p>如果我们需要为Bean设置属性值是另一个Bean实例时，这个时候需要使用ref属性。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=<span class="string">"steelAxe"</span> class=<span class="string">"com.spring.service.impl.SteelAce"</span>&gt;&lt;/bean&gt;</span><br><span class="line">&lt;bean id=<span class="string">"chinese"</span> class=<span class="string">"com.spring.service.impl.Chinese"</span> &gt;</span><br><span class="line">&lt;property name=<span class="string">"axe"</span> <span class="keyword">ref</span>=<span class="string">"steelAxe"</span> /&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure>
<p>早期Spring版本使用ref元素，ref元素可以指定如下两个属性。<br>bean:引用不在同一份XML配置文件中的其他Bean实例的id属性值。<br>local：引用同一份XML配置文件中的其他Bean实例的id属性值。<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=<span class="string">"steelAxe"</span> class=<span class="string">"com.spring.service.impl.SteelAce"</span>&gt;&lt;/bean&gt;</span><br><span class="line">&lt;bean id=<span class="string">"chinese"</span> class=<span class="string">"com.spring.service.impl.Chinese"</span> &gt;</span><br><span class="line">&lt;property name=<span class="string">"axe"</span>&gt;</span><br><span class="line">&lt;<span class="keyword">ref</span> local=<span class="string">"steelAxe"</span>/&gt;</span><br><span class="line">&lt;/property&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure></p>
<h3 id="使用自动装配注入合作者bean">使用自动装配注入合作者bean</h3><p>Spring支持自动装配Bean与Bean之间的依赖关系，也就是说我们无需显示的指定依赖Bean。由BeanFactory检查XML配置文件内容，根据某种规则，为主调Bean注入依赖关系。</p>
<p>Spring的自动装配机制可以通过<code>&lt;bean.../&gt;</code>元素的default-autowire属性指定，也可以通过<code>&lt;bean.../&gt;</code>元素的autowire属性指定。</p>
<p>自动装配可以减少配置文件的工作量，但是它降低了依赖关系的透明性和清晰性，所以一般来说在较大部署环境中不推荐使用，显示配置合作者能够得到更加清晰的依赖关系。Spring提供了如下几种规则来实现自动装配。</p>
<ul>
<li>no:不适用自动装配。Bean依赖必须通过ref元素定义。</li>
<li>byName：根据属性名自动装配。BeanFactory查找容器中的全部Bean，找出其中id属性与属性同名的Bean来完成注入。如果没有找到匹配的Bean实例，则Spring不会进行任何注入。</li>
<li>byType：根据属性类型自动装配。BeanFactory查找容器中的全部Bean，如果正好有一个与依赖属性类型相同的Bean，就自动注入这个属性；但是如果有多个这样的Bean，就会抛出一个异常。如果没有匹配的Bean，则什么都不会发生，属性就不会被设置。如果需要无法自动装配时抛出异常，则设置dependency-check=”objects”。</li>
<li>constructor:与不Type类似，区别是用于构造注入的参数。</li>
<li>autodetect:BeanFactory根据Bean内部结构，决定使用constructor或者byType。如果找到一个默认的构造函数，则使用byType。</li>
</ul>
<h4 id="byName规则">byName规则</h4><p>byName规则是指通过名字注入依赖关系，假如Bean A的实现类里面包含setB()方法，而Spring的配置文件恰好包含一个id为b的Bean，则Spring容器就会将b实例注入Bean A中。如果容器中没有名字匹配的Bean，Spring则不会做任何事情。</p>
<figure class="highlight nix"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean <span class="variable">id=</span><span class="string">"chinese"</span> <span class="variable">class=</span><span class="string">"com.spring.service.impl.Chinese"</span> <span class="variable">autowire=</span><span class="string">"byName"</span> /&gt;</span><br><span class="line">&lt;bean <span class="variable">id=</span><span class="string">"gundog"</span> <span class="variable">class=</span><span class="string">"com.spring.service.impl.Gundog"</span>&gt;</span><br><span class="line">&lt;property <span class="variable">name=</span><span class="string">"name"</span> <span class="variable">value=</span><span class="string">"wangwang"</span> /&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure>
<p>上面的配置文件指定了byName规则。则com.app.service.impl.Chinese类中提供如下的依赖注入方法：<br><figure class="highlight gherkin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">/<span class="keyword">*</span><span class="keyword">*</span></span><br><span class="line"><span class="keyword">*</span> 依赖关系必须的setter方法，因为需要通过名字自动装配</span><br><span class="line"><span class="keyword">*</span> 所以setter方法必须提供set+Bean名，Bean名的首字母大写</span><br><span class="line"><span class="keyword">*</span> <span class="comment">@param dog 设置的dog值</span></span><br><span class="line"><span class="keyword">*</span>/</span><br><span class="line">public void setGundog(Dog dog)&#123;</span><br><span class="line">    this.dog = dog;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="byType规则">byType规则</h4><p>byType规则是根据类型匹配注入依赖关系。假如A实例有setB(B b)方法，而Spring配置文件中恰好有一个类型B的Bean实例，容器为A注入类型匹配的Bean实例。如果容器中存在多个B的实例，则会抛出异常，如果没有B实例，则不会发生任何事情。<br><figure class="highlight nix"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean <span class="variable">id=</span><span class="string">"chinese"</span> <span class="variable">class=</span><span class="string">"com.spring.service.impl.Chinese"</span> <span class="variable">autowire=</span><span class="string">"byType"</span> /&gt;</span><br><span class="line">&lt;bean <span class="variable">id=</span><span class="string">"gundog"</span> <span class="variable">class=</span><span class="string">"com.spring.service.impl.Gundog"</span>&gt;</span><br><span class="line">&lt;property <span class="variable">name=</span><span class="string">"name"</span> <span class="variable">value=</span><span class="string">"wangwang"</span> /&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure></p>
<p>针对上面的配置文件Chinese类有如下方法。<br><figure class="highlight gherkin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">/<span class="keyword">*</span><span class="keyword">*</span></span><br><span class="line"><span class="keyword">*</span> 依赖关系必须的setter方法</span><br><span class="line"><span class="keyword">*</span> 因为使用按类型自动装配，setter方法的参数类型与容器的Bean的类型相同</span><br><span class="line"><span class="keyword">*</span> 程序中的Gundog实现了Dog接口</span><br><span class="line"><span class="keyword">*</span> <span class="comment">@param dog传入的dog对象</span></span><br><span class="line"><span class="keyword">*</span>/</span><br><span class="line">public void setDog(Dog dog)&#123;</span><br><span class="line">    this.dog = dog;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>当一个Bean即使用自动装配依赖，又使用ref显示依赖时，则显示指定的依赖就会覆盖自动装配。</p>
<p>在默认的情况下，Spring会自动搜索容器中的全部Bean，并对这些Bean进行判断，判断他们是否满足自动装配的条件，如果满足就会将该Bean注入目标Bean实例中。如果我们不想让Spring搜索容器中的全部Bean，也就是说，我们需要Spring来判断哪些Bean需要搜索，哪些Bean不需要搜索，这个时候就需要用到autowire-candidate属性。通过为<code>&lt;bean.../&gt;</code>元素设置autowire-candidate=”false”，即可将该Bean限制在自动装配范围之外，容器在查找自动装配对象时将不考虑该Bean。</p>
<h3 id="注入嵌套Bean">注入嵌套Bean</h3><p>如果某个Bean所依赖的Bean不想被Spring容器直接访问，则可以使用嵌套Bean。<code>&lt;bean.../&gt;</code>元素用来定义嵌套Bean，嵌套Bean只对嵌套它的外部Bean有效，Spring容器无法直接访问嵌套Bean，因此在定义嵌套Bean时是无需指定id属性的。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"chinese"</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.Chinese"</span> <span class="attribute">autowire</span>=<span class="value">"byName"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"axe"</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--</span><br><span class="line">属性值为嵌套Bean，嵌套Bean不能由Spring容器直接访问，</span><br><span class="line">所以嵌套Bean是不需要id属性</span><br><span class="line">--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.SteelAce"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>采用上面的配置可以保证嵌套Bean不能被容器访问，因此不用担心其他程序修改嵌套bean。但是嵌套Bean限制了Bean的访问，提高了程序的内聚性。</p>
<h3 id="list、set、map、props">list、set、map、props</h3><p><code>&lt;list.../&gt;</code>、<code>&lt;set.../&gt;</code>、<code>&lt;map.../&gt;</code>和<code>&lt;props.../&gt;</code>元素分别用来设置类型list、set、map和Properties的集合属性值。<br>先看下面java类：<br><figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> class Chinese implements Person&#123;</span><br><span class="line"></span><br><span class="line"><span class="comment">//下面是一系列的集合属性</span></span><br><span class="line"><span class="keyword">private</span> <span class="built_in">List</span><span class="subst">&lt;</span><span class="built_in">String</span><span class="subst">&gt;</span> schools;</span><br><span class="line"><span class="keyword">private</span> <span class="built_in">Map</span> scores;</span><br><span class="line"><span class="keyword">private</span> <span class="built_in">Map</span><span class="subst">&lt;</span><span class="built_in">String</span>, Axe<span class="subst">&gt;</span> phaseAxes;</span><br><span class="line"><span class="keyword">private</span> Properties health;</span><br><span class="line"><span class="keyword">private</span> <span class="built_in">Set</span> axe;</span><br><span class="line"><span class="keyword">private</span> <span class="built_in">String</span><span class="preprocessor">[</span><span class="preprocessor">]</span><span class="markup"> books;</span><br><span class="line">//setter 和getter方法</span><br><span class="line">&#125;</span></span><br></pre></td></tr></table></figure></p>
<p>上面的java代码中有数组、list、set、，map、Properties。下面是针对上面的配置文件。<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">beans</span> <span class="attribute">xmlns:xsi</span>=<span class="value">"http://www.w3.org/2001/XMLSchema-instance"</span></span><br><span class="line"><span class="attribute">xmlns</span>=<span class="value">"http://www.springframework.org/schema/beans"</span></span><br><span class="line"><span class="attribute">xsi:schemaLocation</span>=<span class="value">"http://www.springframework.org/schema/beans</span><br><span class="line">http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 定义一个普通的Axe Bean --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"steelAxe"</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.SteelAxe"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"stoneAxe"</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.StoneAxe"</span> /&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--定义Chinese Bean --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"chinese"</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.Chinese"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"schools"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">list</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">value</span>&gt;</span>小学<span class="tag">&lt;/<span class="title">value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">value</span>&gt;</span>中学<span class="tag">&lt;/<span class="title">value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">value</span>&gt;</span>大学<span class="tag">&lt;/<span class="title">value</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">list</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">property</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"scores"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">map</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">entry</span> <span class="attribute">key</span>=<span class="value">"语文"</span> <span class="attribute">value</span>=<span class="value">"88"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">entry</span> <span class="attribute">key</span>=<span class="value">"数学"</span> <span class="attribute">value</span>=<span class="value">"87"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">entry</span> <span class="attribute">key</span>=<span class="value">"外语"</span> <span class="attribute">value</span>=<span class="value">"88"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">map</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">property</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"phaseAxes"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">map</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">entry</span> <span class="attribute">key</span>=<span class="value">"原始社会"</span> <span class="attribute">value-ref</span>=<span class="value">"stoneAxe"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">entry</span> <span class="attribute">key</span>=<span class="value">"农业社会"</span> <span class="attribute">value-ref</span>=<span class="value">"steelAxe"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">map</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">property</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"health"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">props</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">prop</span> <span class="attribute">key</span>=<span class="value">"血压"</span>&gt;</span>正常<span class="tag">&lt;/<span class="title">prop</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">prop</span> <span class="attribute">key</span>=<span class="value">"身高"</span>&gt;</span>175<span class="tag">&lt;/<span class="title">prop</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">props</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">property</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"axe"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">set</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">value</span>&gt;</span>普通字符串<span class="tag">&lt;/<span class="title">value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.SteelAxe"</span>&gt;</span><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">ref</span> <span class="attribute">local</span>=<span class="value">"stoneAxe"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">set</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">property</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"books"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">list</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">value</span>&gt;</span>java 编程思想<span class="tag">&lt;/<span class="title">value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">value</span>&gt;</span>思考致富<span class="tag">&lt;/<span class="title">value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">value</span>&gt;</span>将才<span class="tag">&lt;/<span class="title">value</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">list</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">beans</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>从上面的配置文件中可以看出，Spring对list属性和数组属性的处理是一样的。</p>
<p>当我们使用<code>&lt;list.../&gt;</code>、<code>&lt;set.../&gt;</code>、<code>&lt;map.../&gt;</code>等元素配置集合属性时，我们还需要手动配置集合元素。由于集合元素又可以是基本类型值、引用容器中的其他Bean、嵌套Bean和集合属性等。所以这些元素又可以接受如下子元素：</p>
<ul>
<li>value:指定集合元素是基本数据类型或者字符类型值。</li>
<li>ref:指定集合元素师容器中另一个Bean实例。</li>
<li>bean:指定集合元素是一个嵌套Bean。</li>
<li>list、set、map、props:指定集合元素值又是集合。</li>
</ul>
<p><code>&lt;props.../&gt;</code>元素用于配置Properties类型的属性，Properties类型是一种特殊的类型，其key和value都只能是字符串。</p>
<p>使用<code>&lt;map.../&gt;</code>元素配置Map属性时比较复杂，因为Map集合的每个元素由key、value两个部分组成，所以配置文件中每个<code>&lt;entry.../&gt;</code>配置一个Map元素，其中entry支持如下4个属性：</p>
<ul>
<li>key：Map的key是基本类型或字符串。</li>
<li>key-ref：Map的key是容器中另一个Bean实例。</li>
<li>value：Map的value是基本类型或字符串。</li>
<li>value-ref：Map的value是容器中另一个Bean实例。</li>
</ul>
<h3 id="组合属性名称">组合属性名称</h3><p>当在配置文件中为Bean属性指定值时，还可以使用组合属性名的方式。例如我们使用如foo.bar.name的属性名，这表明为Bean实例的foo属性的bar属性的name属性指定值。</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public class <span class="keyword">Person</span> &#123;</span><br><span class="line">    private String name;</span><br><span class="line">    //getter .. setter</span><br><span class="line">&#125;</span><br><span class="line">public class ExampleBean &#123;</span><br><span class="line">    private <span class="keyword">Person</span> <span class="keyword">person</span>=new <span class="keyword">Person</span>();</span><br><span class="line">    public <span class="keyword">Person</span> getPerson() &#123;</span><br><span class="line">        return <span class="keyword">person</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>bean.xml核心配置：<br><figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean <span class="property">id</span>=<span class="string">"exampleBean"</span> <span class="type">class</span>=<span class="string">"com.bean.ExampleBean"</span>&gt;</span><br><span class="line">        &lt;<span class="keyword">property</span> <span class="property">name</span>=<span class="string">"person.name"</span> value=<span class="string">"孙悟空"</span>/&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure></p>
<p>除了最后一个属性外，其他属性不能为null，否则引发异常</p>
<p>上面配置片段相当Spring执行：<br><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">exampleBean.getPerson<span class="params">()</span>.setName<span class="params">(<span class="string">"孙悟空"</span>)</span>;</span><br></pre></td></tr></table></figure></p>
<h3 id="Spring的Bean和JavaBean">Spring的Bean和JavaBean</h3><p>Spring容器对Bean没有特殊要求，甚至不要求该Bean像标准的JavaBean那样必须为每个属性提供对应的getter和setter方法。Spring中的Bean是Java实例、Java组件；而传统的Java应用中的JavaBean通常作为DTO(数据传输对象)，用来封装值对象，在各层之间传递数据。</p>
<p>虽然Spring对Bean没有特殊要求，但还是建议Spring中的Bean应该尽量满足如下几个原则：</p>
<ul>
<li>尽量为每个Bean实现类提供无参数的构造器。</li>
<li>接受构造注入的Bean，应该提供对应的构造函数。</li>
<li>接受设值注入的Bean，应该提供对应的setter方法，并不强制要求提供对应的getter方法。</li>
</ul>
<p>传统的JavaBean和Spring中的Bean存在如下区别：</p>
<ul>
<li>用处不同：传统的JavaBean更多作为值对象传递参数；Spring中的Bean用处几乎无所不包，任何应用组件都被称为Bean。</li>
<li>写法不同：传统的JavaBean作为值对象，要求每个属性都提供getter和setter方法；但Spring的Bean只需为接受设值注入的属性提供setter方法。</li>
<li>生命周期不同：传统的JavaBean作为值对象传递，不接受任何容器管理其生命周期；但Spring中的Bean由Spring管理其生命周期行为。</li>
</ul>
<h2 id="Spring_3-0提供的Java配置管理">Spring 3.0提供的Java配置管理</h2><p>Spring允许开发者使用Java类进行配置管理。</p>
<p>假如有如下Person实现类：<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">public class Chinese implements <span class="keyword">Person</span> &#123;</span><br><span class="line">       private Axe axe;</span><br><span class="line">       private String name;</span><br><span class="line">       //设值注入所需的setter方法</span><br><span class="line">       public void setAxe(Axe axe) &#123;</span><br><span class="line">           this.axe = axe;</span><br><span class="line">       &#125;</span><br><span class="line">       //设值注入所需的setter方法</span><br><span class="line">       public void setName(String name) &#123;</span><br><span class="line">           this.name = name;</span><br><span class="line">       &#125;</span><br><span class="line">       //实现<span class="keyword">Person</span>接口的useAxe方法</span><br><span class="line">       public void useAxe() &#123;</span><br><span class="line">           //调用axe的chop()方法，</span><br><span class="line">           //表明<span class="keyword">Person</span>对象依赖于axe对象</span><br><span class="line">           System.out.println(<span class="string">"我是："</span> + name + axe.chop());</span><br><span class="line">       &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面Chinese类需要注入两个属性：name和Axe，本示例当然也为Axe提供了两个实现类：StoneAxe和SteelAxe。如果我们采用XML配置，相应的配置文件如下：<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="GBK"?&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- Spring配置文件的根元素，使用spring-beans-3.0.xsd语义约束 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">beans</span> <span class="attribute">xmlns:xsi</span>=<span class="value">"http://www.w3.org/2001/XMLSchema-instance"</span></span><br><span class="line">       <span class="attribute">xmlns</span>=<span class="value">"http://www.springframework.org/schema/beans"</span></span><br><span class="line">       <span class="attribute">xsi:schemaLocation</span>=<span class="value">"http://www.springframework.org/schema/beans</span><br><span class="line">       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"</span>&gt;</span></span><br><span class="line">       <span class="comment">&lt;!-- 配置chinese实例，其实现类是Chinese --&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"chinese"</span> <span class="attribute">class</span>=<span class="value">"org.crazyit.app.service.impl.Chinese"</span>&gt;</span></span><br><span class="line">                       <span class="comment">&lt;!-- 将stoneAxe注入给axe属性 --&gt;</span></span><br><span class="line">                       <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"axe"</span> <span class="attribute">ref</span>=<span class="value">"stoneAxe"</span>/&gt;</span></span><br><span class="line">                       <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"name"</span> <span class="attribute">value</span>=<span class="value">"孙悟空"</span>/&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line">       <span class="comment">&lt;!-- 配置stoneAxe实例，其实现类是StoneAxe --&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"stoneAxe"</span> <span class="attribute">class</span>=<span class="value">"org.crazyit.app.service.impl.StoneAxe"</span>/&gt;</span></span><br><span class="line">       <span class="comment">&lt;!-- 配置steelAxe实例，其实现类是SteelAxe --&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"steelAxe"</span> <span class="attribute">class</span>=<span class="value">"org.crazyit.app.service.impl.SteelAxe"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">beans</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>如果开发者不喜欢使用XML配置文件，Spring 3.0允许开发者使用Java类进行配置。<br>上面XML配置文件可以替换为如下Java配置类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line">       <span class="comment">//定义需要依赖注入的属性值</span></span><br><span class="line">       <span class="annotation">@Value</span>(<span class="string">"孙悟空"</span>) String personName;</span><br><span class="line">       <span class="comment">//配置一个Bean：chinese</span></span><br><span class="line">       <span class="annotation">@Bean</span>(name=<span class="string">"chinese"</span>)</span><br><span class="line">       <span class="function"><span class="keyword">public</span> Person <span class="title">person</span><span class="params">()</span> </span>&#123;</span><br><span class="line">           Chinese p = <span class="keyword">new</span> Chinese();</span><br><span class="line">           p.setAxe(stoneAxe());</span><br><span class="line">           p.setName(personName);</span><br><span class="line">           <span class="keyword">return</span> p;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="comment">//配置Bean：stoneAxe</span></span><br><span class="line">       <span class="annotation">@Bean</span>(name=<span class="string">"stoneAxe"</span>)</span><br><span class="line">       <span class="function"><span class="keyword">public</span> Axe <span class="title">stoneAxe</span><span class="params">()</span> </span>&#123;</span><br><span class="line">           <span class="keyword">return</span> <span class="keyword">new</span> StoneAxe();</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="comment">//配置Bean：steelAxe</span></span><br><span class="line">       <span class="annotation">@Bean</span>(name=<span class="string">"steelAxe"</span>)</span><br><span class="line">       <span class="function"><span class="keyword">public</span> Axe <span class="title">steelAxe</span><span class="params">()</span> </span>&#123;</span><br><span class="line">           <span class="keyword">return</span> <span class="keyword">new</span> SteelAxe();</span><br><span class="line">       &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面配置文件中使用了Java配置类的3个常用Annotation：</p>
<ul>
<li>@Configuration：用于修饰一个Java配置类。</li>
<li>@Bean：用于修饰一个方法，将该方法的返回值定义成容器中的一个Bean。</li>
<li>@Value：用于修饰一个Field，用于为配置一个值。</li>
</ul>
<p>一旦使用了Java配置类来管理Spring容器中Bean、及其依赖关系，此时需要使用如下方式来创建Spring容器：<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//创建Spring容器</span></span><br><span class="line">ApplicationContext ctx = <span class="keyword">new</span></span><br><span class="line">       AnnotationConfigApplicationContext(AppConfig.<span class="keyword">class</span>);</span><br></pre></td></tr></table></figure></p>
<p>上面AnnotationConfigApplicationContext类会根据Java配置类来创建Spring容器。不仅如此，该类还提供了一个register(Class)方法用于添加Java配置类。</p>
<p>获得Spring容器之后，接下来利用Spring容器获取Bean实例、调用Bean方法就没有任何特别之处了。</p>
<p>使用Java配置类时，还有如下常用的Annotation：</p>
<ul>
<li>@Import：修饰一个Java配置类，用于向当前Java配置类中导入其他Java配置类。</li>
<li>@Scope：用于修饰一个方法，指定该方法对应的Bean的生命域。</li>
<li>@Lazy：用于修饰一个方法，指定该方法对应的Bean的是否需要延迟初始化。</li>
<li>@DependOn：用于修饰一个方法，指定在初始化该方法对应的Bean之前初始化指定Bean。</li>
</ul>
<ol>
<li><p>如果以XML配置为主，就需要让XML配置能加载Java类配置。这并不难，只要在XML配置中增加如下代码即可：</p>
 <figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="GBK"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">beans</span> <span class="attribute">xmlns</span>=<span class="value">"http://www.springframework.org/schema/beans"</span></span><br><span class="line">    <span class="attribute">xmlns:xsi</span>=<span class="value">"http://www.w3.org/2001/XMLSchema-instance"</span></span><br><span class="line">    <span class="attribute">xmlns:context</span>=<span class="value">"http://www.springframework.org/schema/context"</span></span><br><span class="line">    <span class="attribute">xsi:schemaLocation</span>=<span class="value">"http://www.springframework.org/schema/beans</span><br><span class="line">    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd</span><br><span class="line">    http://www.springframework.org/schema/context</span><br><span class="line">    http://www.springframework.org/schema/context/spring-context-3.0.xsd"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">context:annotation-config</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">!—加载Java配置类</span> <span class="attribute">--</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">class</span>=<span class="value">"org.crazyit.app.config.AppConfig”/&gt;</span><br><span class="line">&lt;/beans&gt;</span></span></span><br></pre></td></tr></table></figure>
<p> 由于应用以XML配置为主，因此应用创建Spring容器时，还是以这份XML文件为参数来创建ApplicationContext对象。那么Spring会先加载这份XML配置文件，再根据这份XML配置文件的指示，去加载指定的Java配置类。</p>
</li>
<li><p>如果以Java类配置为主，就需要让Java配置类能加载XML配置。这就需要借助于@ImportResource Annotation，这个Annotation可修饰Java配置类，用于导入指定的XML配置文件。也就是在Java配置类上增加如下Annotation即可：</p>
 <figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">@Configuration</span></span><br><span class="line"><span class="comment">//导入XML配置</span></span><br><span class="line"><span class="variable">@ImportResource</span>(<span class="string">"classpath:/bean.xml"</span>)</span><br><span class="line">public class MyConfig &#123;</span><br><span class="line">    ……</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p> 由于应用以Java类配置为主，因此应用创建Spring容器时，应以Java配置类为参数，创建AnnotationConfigApplicationContext对象来作为Spring容器。那么Spring会先加载这个Java配置类，再根据这个Java配置类的指示，去加载指定的XML配置文件。</p>
</li>
</ol>
<h2 id="Bean实例的创建方式及依赖配置">Bean实例的创建方式及依赖配置</h2><p>创建Bean通常有如下方法：调用构造器，调用静态工厂方法，调用实例工厂方法。</p>
<h3 id="使用构造器创建Bean实例">使用构造器创建Bean实例</h3><p>使用构造器来创建Bean实例是最常见的情况，如果采用设置注入的方式，要求该类提供无参数构造器。class属性是必需的（除非采用继承）</p>
<p>BeanFactory将使用无参数构造器来创建Bean实例，该实例是个默认实例，Spring对Bean实例的所有属性执行默认初始化，即所有基本类型的值初始化为0或false，所有引用类型的值初始化为null。</p>
<p>接下来，BeanFactory会根据配置文件决定依赖关系，先实例化被依赖的Bean实例，然后为Bean注入依赖关系。最后将一个完整的Bean实例返回给程序，该Bean实例的所有属性，已经由Spring容器完成了初始化。</p>
<p>Axe.java :<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title">Axe</span> &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">chop</span>(<span class="params"></span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Person.java :<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public interface <span class="keyword">Person</span> &#123;</span><br><span class="line">    public void useAxe();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>SteelAxe.java :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SteelAxe</span> <span class="keyword">implements</span> <span class="title">Axe</span> </span>&#123;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">chop</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"钢斧砍柴真快"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SteelAxe</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Spring实例化依赖Bean:SteelAxe实例..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Chinese.java :<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Chinese</span> <span class="title">implements</span> <span class="title">Person</span>&#123;</span><br><span class="line">    @<span class="function">Override</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title">useAxe</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        System.<span class="keyword">out</span>.println(axe.chop());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">private</span> Axe axe;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAxe</span>(<span class="params">Axe axe</span>) </span>&#123;</span><br><span class="line">        System.<span class="keyword">out</span>.println(<span class="string">"Spring执行依赖关系注入"</span>);</span><br><span class="line">        <span class="keyword">this</span>.axe = axe;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Chinese</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        System.<span class="keyword">out</span>.println(<span class="string">"Spring实例化主调Bean:Chinese实例..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>bean.xml核心配置 :<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=<span class="string">"chinese"</span> class=<span class="string">"com.bean.Chinese"</span>&gt;</span><br><span class="line">    &lt;property name=<span class="string">"axe"</span> <span class="keyword">ref</span>=<span class="string">"steelAxe"</span>/&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line"></span><br><span class="line">&lt;bean id=<span class="string">"steelAxe"</span> class=<span class="string">"com.bean.SteelAxe"</span>/&gt;</span><br></pre></td></tr></table></figure></p>
<p>Test.java :<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public class Test &#123;</span><br><span class="line">    public static void main(String<span class="comment">[]</span> args) &#123;</span><br><span class="line">        ApplicationContext ctx=new ClassPathXmlApplicationContext(<span class="string">"bean.xml"</span>);</span><br><span class="line">        <span class="keyword">Person</span> <span class="keyword">person</span>=(<span class="keyword">Person</span>) ctx.getBean(<span class="string">"chinese"</span>);</span><br><span class="line">        <span class="keyword">person</span>.useAxe();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">//控制台输出：</span><br><span class="line">Spring实例化主调Bean:Chinese实例...</span><br><span class="line">Spring实例化依赖Bean:SteelAxe实例...</span><br><span class="line">Spring执行依赖关系注入</span><br><span class="line">钢斧砍柴真快</span><br></pre></td></tr></table></figure></p>
<p>执行结果清楚地反映了执行过程：</p>
<ol>
<li>程序创建ApplicationContext实例。</li>
<li>调用Chinese类的默认构造器创建默认实例。</li>
<li>根据配置文件注入依赖关系：先实例化依赖Bean，然后将依赖Bean注入。</li>
<li>返回一个完整的Chinese实例。</li>
</ol>
<h3 id="使用静态工厂方法创建Bean">使用静态工厂方法创建Bean</h3><p>Being.java :<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title">Being</span> &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testBeing</span>(<span class="params"></span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Dog.java :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Dog</span> <span class="keyword">implements</span> <span class="title">Being</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String msg;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMsg</span><span class="params">(String msg)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.msg = msg;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testBeing</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(msg+<span class="string">",狗爱啃骨头"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Cat.java :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Cat</span> <span class="keyword">implements</span> <span class="title">Being</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String msg;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMsg</span><span class="params">(String msg)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.msg = msg;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testBeing</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(msg+<span class="string">",猫爱吃老鼠"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>BeingFactory.java :</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">BeingFactory</span> &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Being <span class="title">getBeing</span>(<span class="params">String arg</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(arg.equalsIgnoreCase(<span class="string">"dog"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Dog();</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Cat();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>bean.xml核心配置：<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=<span class="string">"dog"</span> class=<span class="string">"com.bean.BeingFactory"</span> factory-<span class="keyword">method</span>=<span class="string">"getBeing"</span>&gt;</span><br><span class="line">    &lt;constructor-arg value=<span class="string">"dog"</span>/&gt;</span><br><span class="line">    &lt;property name=<span class="string">"msg"</span> value=<span class="string">"我是狗"</span>/&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line"></span><br><span class="line">&lt;bean id=<span class="string">"cat"</span> class=<span class="string">"com.bean.BeingFactory"</span> factory-<span class="keyword">method</span>=<span class="string">"getBeing"</span>&gt;</span><br><span class="line">    &lt;constructor-arg value=<span class="string">"cat"</span>/&gt;</span><br><span class="line">    &lt;property name=<span class="string">"msg"</span> value=<span class="string">"我是猫"</span>/&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure></p>
<p>从上面的核心配置可以看出，cat和dog两个Bean配置的class属性和factory-method属性完全相同，这是因为这两个实例都是由同一个工厂类的同一个静态方法生产得到的。配置这两个Bean实例指定了工厂的静态方法的实参值不同，配置静态方法的实参值使用<code>&lt;constructor-arg.../&gt;</code>元素。<br>Test.java :<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Test</span> &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span>(<span class="params">String[] args</span>) </span>&#123;</span><br><span class="line">        ApplicationContext ctx=<span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">"bean.xml"</span>);</span><br><span class="line">        Being b1=(Being) ctx.getBean(<span class="string">"dog"</span>);</span><br><span class="line">        b1.testBeing();</span><br><span class="line">        Being b2=(Being) ctx.getBean(<span class="string">"cat"</span>);</span><br><span class="line">        b2.testBeing();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>使用静态工厂方法创建Bean实例时，class属性也必须指定，但此时class属性并不是Bean实例的实现类，而是静态工厂类。除此之外，还需要使用factory-method属性来指定工厂的静态方法名。</p>
<h3 id="调用实例工厂方法创建Bean">调用实例工厂方法创建Bean</h3><p>Person.java :<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public interface <span class="keyword">Person</span> &#123;</span><br><span class="line">    public String sayHello(String name);</span><br><span class="line">    public String sayGoodBye(String name);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Chinese.java :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Chinese</span> <span class="keyword">implements</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">sayGoodBye</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> name+<span class="string">",再见！"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">sayHello</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> name+<span class="string">",你好"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>American.java :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">American</span> <span class="keyword">implements</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">sayGoodBye</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> name+<span class="string">",Good Bye !"</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">sayHello</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> name+<span class="string">",Hello !"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>PersonFactory.java :<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">PersonFactory</span> &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Person <span class="title">getPerson</span>(<span class="params">String ethnic</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(ethnic.equalsIgnoreCase(<span class="string">"chin"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Chinese();</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> American();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>bean.xml核心配置 :<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=<span class="string">"personFactory"</span> class=<span class="string">"com.bean.PersonFactory"</span>/&gt;</span><br><span class="line">&lt;bean id=<span class="string">"chinese"</span> factory-bean=<span class="string">"personFactory"</span> factory-<span class="keyword">method</span>=<span class="string">"getPerson"</span>&gt;</span><br><span class="line">    &lt;constructor-arg value=<span class="string">"chin"</span>/&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line"></span><br><span class="line">&lt;bean id=<span class="string">"american"</span> factory-bean=<span class="string">"personFactory"</span> factory-<span class="keyword">method</span>=<span class="string">"getPerson"</span>&gt;</span><br><span class="line">    &lt;constructor-arg value=<span class="string">"ame"</span>/&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure></p>
<p>Test.java :<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">public class Test &#123;</span><br><span class="line">    public static void main(String<span class="comment">[]</span> args) &#123;</span><br><span class="line">        ApplicationContext ctx=new ClassPathXmlApplicationContext(<span class="string">"bean.xml"</span>);</span><br><span class="line">        <span class="keyword">Person</span> p1=(<span class="keyword">Person</span>) ctx.getBean(<span class="string">"chinese"</span>);</span><br><span class="line">        System.out.println(p1.sayGoodBye(<span class="string">"tom"</span>)+p1.sayHello(<span class="string">"tom"</span>));</span><br><span class="line">        <span class="keyword">Person</span> p2=(<span class="keyword">Person</span>) ctx.getBean(<span class="string">"american"</span>);</span><br><span class="line">        System.out.println(p2.sayGoodBye(<span class="string">"tom"</span>)+p2.sayHello(<span class="string">"tom"</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>实例工厂方法与静态工厂方法的区别。</p>
<p>调用实例工厂方法创建Bean，必须将实例工厂配置成Bean实例。而静态工厂方法创建Bean，则无需配置工厂Bean。<br>调用实例工厂方法创建Bean，必须使用factory-bean属性确定工厂Bean。而静态工厂方法创建Bean，则使用class元素确定静态工厂类。</p>
<h2 id="深入理解容器中的Bean">深入理解容器中的Bean</h2><h3 id="使用抽象Bean">使用抽象Bean</h3><p>抽象Bean，都是指定abstract属性为true的Bean，抽象Bean不能被实例化，Spring容器不会创建抽象Bean的实例。抽象Bean的价值在于被继承，抽象Bean通常作为父Bean被继承。<br>当某个Bean将作为其他Bean的模板使用时，该Bean通常不需要实例化，而ApplicationContext默认预初始化所有的singleton Bean。为了阻止Bean模板被预初始化，可以指定abstract=“true”将该模板Bean设置为抽象Bean，Spring容器会忽略所有的抽象Bean定义，预初始化时不初始化抽象Bean。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=<span class="string">"chineseTemplate"</span> class=<span class="string">"com.bean.Chinese"</span> abstract=<span class="string">"true"</span>&gt;</span><br><span class="line">   &lt;property name=<span class="string">"axe"</span> <span class="keyword">ref</span>=<span class="string">"steelAxe"</span>/&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line">&lt;bean id=<span class="string">"steelAxe"</span> class=<span class="string">"com.bean.SteelAxe"</span>/&gt;</span><br></pre></td></tr></table></figure>
<p>这样配置以后，当程序采用ApplicationContext作为Spring容器时，程序实例化ApplicationContext容器时会默认实例化所有的singleton Bean，但不会初始化abstract  Bean。<br>抽象Bean是一个模板，容器会忽略抽象Bean的定义，不会实例化抽象Bean。抽象Bean因为无须实例化，因此可以没有class属性。<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=<span class="string">"chineseTemplate"</span> abstract=<span class="string">"true"</span>&gt;</span><br><span class="line">   &lt;property name=<span class="string">"axe"</span> <span class="keyword">ref</span>=<span class="string">"steelAxe"</span>/&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line">&lt;bean id=<span class="string">"steelAxe"</span> class=<span class="string">"com.bean.SteelAxe"</span>/&gt;</span><br></pre></td></tr></table></figure></p>
<p>抽象Bean不能实例化，因此既不能通过getBean显式地获得抽象Bean实例，也不能将抽象Bean注入成其他Bean的依赖属性。无论何时，只要企图实例化抽象Bean，都将导致错误。</p>
<h3 id="使用子Bean">使用子Bean</h3><p>现象：有一批Bean配置的大量配置信息完全相同，只有少量配置不同。那么我们是否有办法来简化配置呢？Spring提供了 Bean继承来应对这个问题。Spring可以先为这批Bean配置一个Bean模板，将这批Bean中相同的配置信息配置成Bean模板，因为Spring容器无须创建Bean模板的实例，所以通常将这个Bean模板配成抽象Bean。</p>
<p>将大部分相同信息配置成Bean模板后，将实际的Bean实例配置成Bean模板的子Bean即可。子Bean定义可以从父Bean继承实现类、构造器参数、属性值等配置信息，除此之外，子Bean配置可以增加新的配置信息，并可指定新的配置信息覆盖父Bean的定义。</p>
<p>子Bean无法从父Bean继承如下属性：depends-on、autowire、singleton、scope、lazy-init，这些属性将总是从子Bean定义中获得，或采取默认值。</p>
<p>通过为一个<code>&lt;bean.../&gt;</code>元素指定 parent属性 即可指定该Bean是一个子Bean，parent属性指定该Bean所继承的父Bean的id。</p>
<p>Axe.java :<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title">Axe</span> &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">chop</span>(<span class="params"></span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>SteelAxe.java :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SteelAxe</span> <span class="keyword">implements</span> <span class="title">Axe</span> </span>&#123;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">chop</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"钢斧砍柴真快"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SteelAxe</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Spring实例化依赖bean:SteelAxe实例..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>StoneAxe.java :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StoneAxe</span> <span class="keyword">implements</span> <span class="title">Axe</span> </span>&#123;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">chop</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"石斧砍柴真慢"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">StoneAxe</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Spring实例化依赖bean:StoneAxe实例..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Person.java :<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public interface <span class="keyword">Person</span> &#123;</span><br><span class="line">    public void useAxe();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Chinese.java :<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Chinese</span> <span class="title">implements</span> <span class="title">Person</span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Axe axe;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAxe</span>(<span class="params">Axe axe</span>) </span>&#123;</span><br><span class="line">        System.<span class="keyword">out</span>.println(<span class="string">"Spring执行依赖关系注入..."</span>);</span><br><span class="line">        <span class="keyword">this</span>.axe = axe;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Chinese</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        System.<span class="keyword">out</span>.println(<span class="string">"Spring实例化主调bean:Chinese实例..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    @<span class="function">Override</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title">useAxe</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        System.<span class="keyword">out</span>.println(axe.chop());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>bean.xml核心配置：<br><figure class="highlight nix"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean <span class="variable">id=</span><span class="string">"steelAxe"</span> <span class="variable">class=</span><span class="string">"com.bean.SteelAxe"</span>/&gt;</span><br><span class="line">&lt;bean <span class="variable">id=</span><span class="string">"stoneAxe"</span> <span class="variable">class=</span><span class="string">"com.bean.StoneAxe"</span>/&gt;</span><br><span class="line"></span><br><span class="line">&lt;bean <span class="variable">id=</span><span class="string">"chineseTemplate"</span> <span class="variable">class=</span><span class="string">"com.bean.Chinese"</span> <span class="variable">abstract=</span><span class="string">"true"</span>&gt;</span><br><span class="line">   &lt;property <span class="variable">name=</span><span class="string">"axe"</span> <span class="variable">ref=</span><span class="string">"steelAxe"</span>/&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line">&lt;bean <span class="variable">id=</span><span class="string">"chinese"</span> <span class="variable">parent=</span><span class="string">"chineseTemplate"</span>/&gt;</span><br></pre></td></tr></table></figure></p>
<p>Test.java :<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">public class Test &#123;</span><br><span class="line">    public static void main(String<span class="comment">[]</span> args) &#123;</span><br><span class="line">        ApplicationContext ctx=new ClassPathXmlApplicationContext(<span class="string">"bean.xml"</span>);</span><br><span class="line">        <span class="keyword">Person</span> p=(<span class="keyword">Person</span>) ctx.getBean(<span class="string">"chinese"</span>);</span><br><span class="line">        p.useAxe();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">//控制台输出：</span><br><span class="line">Spring实例化依赖bean：SteelAxe实例...</span><br><span class="line">Spring实例化依赖bean：StoneAxe实例...</span><br><span class="line">Spring实例化主调bean：Chinese实例...</span><br><span class="line">Spring执行依赖关系注入...</span><br><span class="line">钢斧砍柴真快</span><br></pre></td></tr></table></figure></p>
<p>子Bean从父Bean继承了实现类，依赖关系等配置信息。实际上，子Bean也可以覆盖父Bean的配置信息：<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=<span class="string">"steelAxe"</span> class=<span class="string">"com.bean.SteelAxe"</span>/&gt;</span><br><span class="line">&lt;bean id=<span class="string">"stoneAxe"</span> class=<span class="string">"com.bean.StoneAxe"</span>/&gt;</span><br><span class="line"></span><br><span class="line">&lt;bean id=<span class="string">"chineseTemplate"</span> class=<span class="string">"com.bean.Chinese"</span> abstract=<span class="string">"true"</span>&gt;</span><br><span class="line">   &lt;property name=<span class="string">"axe"</span> <span class="keyword">ref</span>=<span class="string">"steelAxe"</span>/&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line">&lt;bean id=<span class="string">"chinese"</span> parent=<span class="string">"chineseTemplate"</span>&gt;</span><br><span class="line">   &lt;property name=<span class="string">"axe"</span> <span class="keyword">ref</span>=<span class="string">"stoneAxe"</span>/&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure></p>
<p>控制台输出：<br><figure class="highlight erlang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">Spring</span>实例化依赖bean：<span class="variable">SteelAxe</span>实例...</span><br><span class="line"><span class="variable">Spring</span>实例化依赖bean：<span class="variable">StoneAxe</span>实例...</span><br><span class="line"><span class="variable">Spring</span>实例化主调bean：<span class="variable">Chinese</span>实例...</span><br><span class="line"><span class="variable">Spring</span>执行依赖关系注入...</span><br><span class="line">石斧砍柴真慢</span><br></pre></td></tr></table></figure></p>
<h3 id="Bean继承与Java继承的区别">Bean继承与Java继承的区别</h3><p>Spring中的Bean继承与Java中的继承截然不同。前者是实例与实例之间的参数的延续，后者则是一般到特殊的细化；前者是对象与对象之间的关系，后者是类与类之间的关系。Spring中的Bean继承与Java中的继承有如下区别：</p>
<ol>
<li>Spring中子Bean和父Bean可以是不同类型，但Java中的继承则可保证子类是一种特殊的父类。</li>
<li>Spring中的Bean继承是实例之间的关系，因此主要表现为参数值的延续；而Java中的继承是类之间的关系，主要表现为方法、属性的延续。</li>
<li>Spring中子Bean不可作为父Bean使用，不具备多态性；Java中的子类实例完全可以当成父类实例使用。</li>
</ol>
<h3 id="容器中的_工厂Bean">容器中的 工厂Bean</h3><p>此处的工厂Bean，与前面介绍的实例工厂方法创建Bean，或者静态工厂方法创建Bean的工厂有所区别：前面那些工厂是标准的工厂模式，Spring只是负责调用工厂方法来创建Bean实例；此处的工厂Bean是Spring的一种特殊Bean，这种工厂Bean必须实现FactoryBean接口。</p>
<p>FactoryBean接口是工厂Bean的标准接口，实现该接口的Bean通常只能作为工厂Bean使用，当我们将工厂Bean部署在容器中，并通过getBean( )方法来获取工厂Bean时，容器不会返回FactoryBean实例，而是返回FactoryBean的产品。</p>
<p>FactoryBean接口提供如下三个方法：</p>
<ul>
<li>Object getObject( )    实现该方法负责返回该工厂Bean生成的Java实例。</li>
<li>Class getObjectType( )    实现该方法返回该工厂Bean生成的Java实例的实现类。</li>
<li>boolean isSingleton( )    实现该方法表示该工厂Bean生成的Java实例是否为单例模式。 实现FactoryBean接口的Bean无法作为正常Bean使用，配置FactoryBean与配置普通Bean没有区别，但当客户端对该Bean id请求时，容器返回该FactoryBean的产品，而不是返回该FactoryBean本身。</li>
</ul>
<p>Person.java :<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public interface <span class="keyword">Person</span> &#123;</span><br><span class="line">    public String sayHello(String name);</span><br><span class="line">    public String sayGoodBye(String name);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Chinese.java :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Chinese</span> <span class="keyword">implements</span> <span class="title">Person</span></span>&#123;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">sayGoodBye</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"再见,"</span>+name;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">sayHello</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"你好,"</span>+name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>PersonFactory.java :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PersonFactory</span> <span class="keyword">implements</span> <span class="title">FactoryBean</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Person p;</span><br><span class="line">    <span class="comment">//返回工厂Bean所生产的产品</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Person <span class="title">getObject</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(p==<span class="keyword">null</span>)&#123;</span><br><span class="line">            p=<span class="keyword">new</span> Chinese();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> p;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//获取工厂Bean所生产的产品的类型</span></span><br><span class="line">    <span class="keyword">public</span> Class&lt;?&gt; getObjectType() &#123;</span><br><span class="line">        <span class="keyword">return</span> Chinese.class;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//返回该工厂Bean所生产的产品是否为单例</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isSingleton</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>bean.xml核心配置：<br><figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean <span class="property">id</span>=<span class="string">"chinese"</span> <span class="type">class</span>=<span class="string">"com.bean.PersonFactory"</span>/&gt;</span><br></pre></td></tr></table></figure></p>
<p>Test.java :<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">public class Test &#123;</span><br><span class="line">    public static void main(String<span class="comment">[]</span> args) &#123;</span><br><span class="line">        ApplicationContext ctx=new ClassPathXmlApplicationContext(<span class="string">"bean.xml"</span>);</span><br><span class="line">        //直接请求FactoryBean时，系统将返回该FactoryBean的产品</span><br><span class="line">        <span class="keyword">Person</span> p1=(<span class="keyword">Person</span>) ctx.getBean(<span class="string">"chinese"</span>);//1</span><br><span class="line">        System.out.println(p1.sayHello(<span class="string">"汤姆"</span>));</span><br><span class="line">        System.out.println(p1.sayGoodBye(<span class="string">"汤姆"</span>));</span><br><span class="line">        //再次获取该FactoryBean的产品</span><br><span class="line">        <span class="keyword">Person</span> p2=(<span class="keyword">Person</span>) ctx.getBean(<span class="string">"chinese"</span>);//2</span><br><span class="line">        System.out.println(p1==p2);</span><br><span class="line">        System.out.println(ctx.getBean(<span class="string">"&amp;chinese"</span>));//3</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">///控制台输出：</span><br><span class="line">你好，汤姆</span><br><span class="line">再见，汤姆</span><br><span class="line">true</span><br><span class="line">com.bean.PersonFactory@5e5a50</span><br></pre></td></tr></table></figure></p>
<p>上面的PersonFactory是一个标准的工厂Bean，该PersonFactory的getObject( )方法保证每次产生的Person对象是单例的，故该工厂类的isSingleton( )方法返回true。</p>
<p>Test.java中1和2直接请求容器中的FactoryBean，Spring将不会返回该FactoryBean实例，而是返回该FactoryBean的产品；程序3在Bean id前增加&amp;符号，这将会让Spring返回FactoryBean本身。</p>
<p>因为FactoryBean以单例方式管理产品Bean，因此两次请求的产品，是同一个共享实例。</p>
<p>当程序需要获取FactoryBean本身时，并不直接请求Bean id，而是在Bean id前增加&amp;符号。</p>
<p>对于初学者而言，可能无法体会到工厂Bean的作用。实际上，FactoryBean是Spring中非常有用的一个接口，Spring内置提供了很多实用的工厂Bean，例如TransactionProxyFactoryBean等，这个工厂Bean专门用于为目标Bean创建事务代理。</p>
<p>Spring提供的工厂Bean，大多以FactoryBean后缀结尾，Spring提供的工厂Bean，大多用于生产一批具有某种特征的Bean实例，工厂Bean是Spring的一个重要工具类。</p>
<h3 id="获得Bean部署时的id">获得Bean部署时的id</h3><p>在某些极端情况下，程序开发Bean类时需要获得在容器中部署该Bean时指定的id属性，此时可借助于Spring提供的 BeanNameAware 接口，通过该接口允许Bean类获取部署该Bean时指定的id属性。</p>
<p>BeanNameAware接口提供的一个方法：setBeanName(String name)，该方法的name参数就是Bean的id，实现该方法的Bean类就可通过该方法来获得部署该Bean的id了。</p>
<p>Chinese.java :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Chinese</span> <span class="keyword">implements</span> <span class="title">BeanNameAware</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String beanName;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setBeanName</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.beanName=name;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">getBeanId</span><span class="params">()</span></span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Chinese实现类，部署该Bean时指定的id为："</span>+beanName);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>bean.xml 核心配置：<br><figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean <span class="property">id</span>=<span class="string">"chinese"</span> <span class="type">class</span>=<span class="string">"com.bean.Chinese"</span>/&gt;</span><br></pre></td></tr></table></figure></p>
<p>Test.java :<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Test</span> &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span>(<span class="params">String[] args</span>) </span>&#123;</span><br><span class="line">        ApplicationContext ctx=<span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">"bean.xml"</span>);</span><br><span class="line">        Chinese c=(Chinese) ctx.getBean(<span class="string">"chinese"</span>);</span><br><span class="line">        c.getBeanId();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment"><span class="xmlDocTag">///</span>控制台输出：</span></span><br><span class="line">Chinese实现类，部署该Bean时指定的id为:chinese</span><br></pre></td></tr></table></figure></p>
<p>Spring容器何时回调Bean实例的setBeanName(String name)方法呢？Spring容器会在Bean初始化完成后回调该方法—这里的初始化指的是Bean的初始化行为：包括回调实现InitializingBean接口所实现的afterPropertiesSet方法，回调Bean配置中init-method属性指定的方法。当Spring容器完成了Bean的初始化动作之后，接下来将会回调实现BeanNameAware接口里的setBeanName(String name)方法。</p>
<h3 id="强制初始化Bean">强制初始化Bean</h3><p>Spring默认有个规则：总是先初始化主调Bean，然后再初始化依赖Bean。</p>
<p>大多数情况下，Bean之间的依赖关系非常直接，Spring容器在返回Bean实例之前，完成Bean依赖关系的注入。假如Bean A依赖于Bean B，程序请求Bean A时，Spring容器会自动先初始化Bean B，再将Bean B注入Bean A，最后将具备完整依赖的Bean A返回给程序。</p>
<p>在极端的情况下，Bean之间的依赖不够直接。比如某个类的初始化块中使用其他Bean，Spring总是先初始化主调Bean，执行初始化块时还没有实例化主调Bean，被依赖的Bean还没实例化，此时将引发异常。</p>
<p>为了让指定Bean在目标Bean之前初始化，可以使用 depends-on 属性，该属性可以在初始化主调Bean之前，强制初始化一个或多个Bean。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=<span class="string">"beanOne"</span> class=<span class="string">"ExampleBean"</span> depends-on=<span class="string">"manager"</span>&gt;</span><br><span class="line">    &lt;property name=<span class="string">"manager"</span> <span class="keyword">ref</span>=<span class="string">"manager"</span>/&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line">&lt;bean id=<span class="string">"manager"</span> class=<span class="string">"ManagerBean"</span>/&gt;</span><br></pre></td></tr></table></figure>
<h2 id="容器中Bean的生命周期">容器中Bean的生命周期</h2><p>对于singleton作用域的Bean，Spring容器知道Bean何时实例化结束、何时销毁，Spring可以管理实例化结束之后和销毁之前的行为。管理Bean的生命周期行为主要有如下两个时机：</p>
<ol>
<li>注入依赖关系之后。</li>
<li>即将销毁Bean之前。</li>
</ol>
<h3 id="依赖关系注入之后的行为">依赖关系注入之后的行为</h3><p>依赖关系注入之后的行为：<br>Spring提供两种方式在Bean全部属性设置成功后执行特定行为：</p>
<ol>
<li>使用 init-method 属性<br> 使用init-method属性指定某个方法应在Bean全部依赖关系设置结束后自动执行，使用这种方法不需将代码与Spring的接口耦合在一起，代码污染小。</li>
<li>实现 InitializingBean 接口<br> 该接口提供一个方法，void afterPropertiesSet( )throws Exception。Spring容器会在为该Bean注入依赖关系之后，接下来会调用该Bean所实现的afetrPropertiesSet( )方法。</li>
</ol>
<p>Axe.java :<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title">Axe</span> &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">chop</span>(<span class="params"></span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Person.java :<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public interface <span class="keyword">Person</span> &#123;</span><br><span class="line">    public void useAxe();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>SteelAxe.java :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SteelAxe</span> <span class="keyword">implements</span> <span class="title">Axe</span> </span>&#123;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">chop</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"钢斧砍柴真快"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SteelAxe</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Spring实例化依赖bean:SteelAxe实例..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Chinese.java :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Chinese</span> <span class="keyword">implements</span> <span class="title">Person</span>,<span class="title">InitializingBean</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Axe axe;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Chinese</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Spring实例化主调Bean:Chinese实例..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAxe</span><span class="params">(Axe axe)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Spring执行依赖关系注入..."</span>);</span><br><span class="line">        <span class="keyword">this</span>.axe = axe;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">useAxe</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(axe.chop());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span></span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"正在执行初始化方法init..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"正在执行初始化方法afterPropertiesSet..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>bean.xml 核心配置：<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=<span class="string">"chinese"</span> class=<span class="string">"com.bean.Chinese"</span> init-<span class="keyword">method</span>=<span class="string">"init"</span>&gt;</span><br><span class="line">    &lt;property name=<span class="string">"axe"</span> <span class="keyword">ref</span>=<span class="string">"steelAxe"</span>&gt;&lt;/property&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line"></span><br><span class="line">&lt;bean id=<span class="string">"steelAxe"</span> class=<span class="string">"com.bean.SteelAxe"</span>/&gt;</span><br></pre></td></tr></table></figure></p>
<p>Test.java :<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">public class Test &#123;</span><br><span class="line">    public static void main(String<span class="comment">[]</span> args) &#123;</span><br><span class="line">        ApplicationContext ctx=new ClassPathXmlApplicationContext(<span class="string">"bean.xml"</span>);</span><br><span class="line">        <span class="keyword">Person</span> p=(<span class="keyword">Person</span>) ctx.getBean(<span class="string">"chinese"</span>);</span><br><span class="line">        p.useAxe();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>从运行结果可以看出：依赖注入完成之后，程序先调用afterPropertiesSet方法，再调用init-method属性所指定的方法进行初始化。</p>
<h3 id="Bean_销毁之前的行为">Bean 销毁之前的行为</h3><p>与定制初始化行为相似，Spring也提供两种方法定制Bean实例销毁之前的行为：</p>
<ol>
<li>使用destroy-method属性：<br> destroy-method属性指定某个方法在Bean销毁之前被自动执行。使用这种方式，不需要将代码与Spring的接口耦合，代码污染小。</li>
<li>实现DisposableBean接口：<br> 该接口提供了一个方法，void destroy( ) throws Exception，该方法就是Bean实例被销毁之前应该执行的方法。</li>
</ol>
<p>Axe.java :<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title">Axe</span> &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">chop</span>(<span class="params"></span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Person.java :<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public interface <span class="keyword">Person</span> &#123;</span><br><span class="line">    public void useAxe();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>SteelAxe.java :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SteelAxe</span> <span class="keyword">implements</span> <span class="title">Axe</span> </span>&#123;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">chop</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"钢斧砍柴真快"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SteelAxe</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Spring实例化依赖Bean:SteelAxe实例..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Chinese.java :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Chinese</span> <span class="keyword">implements</span> <span class="title">Person</span>,<span class="title">DisposableBean</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Axe axe;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Chinese</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Spring实例化主调Bean:Chinese实例..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAxe</span><span class="params">(Axe axe)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Spring执行依赖关系注入..."</span>);</span><br><span class="line">        <span class="keyword">this</span>.axe = axe;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">useAxe</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(axe.chop());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">close</span><span class="params">()</span></span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"正在执行销毁之前的方法close..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">destroy</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"正在执行销毁之前的方法destroy..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>bean.xml核心配置：<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=<span class="string">"chinese"</span> class=<span class="string">"com.bean.Chinese"</span> destroy-<span class="keyword">method</span>=<span class="string">"close"</span>&gt;</span><br><span class="line">   &lt;property name=<span class="string">"axe"</span> <span class="keyword">ref</span>=<span class="string">"steelAxe"</span>&gt;&lt;/property&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line"></span><br><span class="line">&lt;bean id=<span class="string">"steelAxe"</span> class=<span class="string">"com.bean.SteelAxe"</span>/&gt;</span><br></pre></td></tr></table></figure></p>
<p>Test.java :<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public class Test &#123;</span><br><span class="line">    public static void main(String<span class="comment">[]</span> args) &#123;</span><br><span class="line">        AbstractApplicationContext ctx=new ClassPathXmlApplicationContext(<span class="string">"bean.xml"</span>);</span><br><span class="line">        <span class="keyword">Person</span> p=(<span class="keyword">Person</span>) ctx.getBean(<span class="string">"chinese"</span>);</span><br><span class="line">        p.useAxe();</span><br><span class="line">        ctx.registerShutdownHook();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>singleton 作用域的Bean通常会随容器的关闭而销毁，但问题是：ApplicationContext容器在什么时候关闭呢？在基于web的ApplicationContext实现中，系统已经提供了相应的代码保证关闭web应用时恰当地关闭Spring容器。</p>
<p>如果处于一个非web应用的环境下，为了让Spring容器优雅地关闭，并调用singleton Bean上的相应析构回调方法，则需要在JVM虚拟机里注册一个关闭钩子，这样就可保证Spring容器被恰当关闭，且自动执行singleton Bean实例的析构回调方法。</p>
<p>为了注册关闭钩子，只需要调用在AbstractApplicationContext中提供的registerShutdownHook( )方法即可。</p>
<p>从程序的输出可以看出：Spring容器注入之后，关闭之前，程序先调用destroy方法进行回收资源，再调用close方法进行回收资源。</p>
<p>如果某个Bean类实现了DisposableBean接口，在Bean被销毁之前，Spring容器会自动调用该Bean实例的destroy方法，其结果与采用destroy-method属性指定生命周期方法几乎一样。但实现DisposableBean接口污染了代码，是侵入式设计，因此不推荐使用。</p>
<p>除此之外，如果容器中很多Bean都需要指定特定的生命周期行为，则可以利用 <code>&lt;beans.../&gt;</code> 元素的 default-init-method属性和 default-destroy-method 属性，这两个属性的作用类似于 <code>&lt;bean.../&gt;</code>元素的 init-method 属性和destroy-method 属性，区别是default-init-method和default-destroy-method是针对容器中所有Bean生效。</p>
<h3 id="协调作用域不同步的Bean">协调作用域不同步的Bean</h3><p>当两个singleton作用域Bean存在依赖关系时，或prototype作用域Bean依赖singleton作用域Bean时，不会有任何问题。</p>
<p>但当singleton作用域Bean依赖prototype作用域Bean时，singleton作用域Bean只有一次初始化的机会，它的依赖关系也只在初始化阶段被设置，它所依赖的prototype作用域Bean则需要每次都得到一个全新的Bean实例，这将会导致singleton作用域的Bean的依赖得不到即时更新。</p>
<p>由于singleton Bean具有单例行为，当客户端多次请求singleton Bean时，Spring返回给客户端的将是同一个singleton Bean实例，这不存在任何问题。问题是：如果客户端多次请求singleton Bean、并调用singleton Bean去调用prototype Bean的方法时，始终都是调用同一个prototype Bean实例，这就违背了设置prototype Bean的初衷：本来希望它具有prototype行为，但实际上它却表现出singleton行为。</p>
<p>这就是问题的所在：当singleton作用域的Bean依赖于prototype作用域的Bean时，会产生不同步的现象。</p>
<p>解决该问题有如下两种思路：</p>
<ol>
<li>部分放弃依赖注入：singleton作用域Bean每次需要prototype作用域Bean时，主动向容器请求新的Bean实例，即可保证每次注入的prototype Bean实例都是最新的实例。</li>
<li>利用方法注入。<br>第一种方式显然不是一个好的做法，代码主动请求新的Bean实例，必然导致代码与Spring API耦合，造成代码严重污染。<br>通常情况下，我们采用第二种做法，使用方法注入。方法注入通常使用lookup方法注入，利用lookup方法注入可以让Spring容器重写容器中Bean的抽象或具体方法，返回查找容器中其他Bean的结果，被查找的Bean通常是一个non-singleton Bean。Spring通过使用CGLIB库修改客户端的二进制码，从而实现上述的要求。</li>
</ol>
<p>Axe.java :<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title">Axe</span> &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">chop</span>(<span class="params"></span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>SteelAxe.java :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SteelAxe</span> <span class="keyword">implements</span> <span class="title">Axe</span> </span>&#123;</span><br><span class="line">    <span class="annotation">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">chop</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"钢斧砍柴真快"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SteelAxe</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Spring实例化依赖Bean:SteelAxe实例..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Person.java :<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public interface <span class="keyword">Person</span> &#123;</span><br><span class="line">    public void useAxe();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Chinese.java :<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title">Chinese</span> <span class="title">implements</span> <span class="title">Person</span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Chinese</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        System.<span class="keyword">out</span>.println(<span class="string">"Spring实例化主调Bean:Chinese实例..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//singleton Bean里增加一个抽象方法</span></span><br><span class="line">    <span class="comment">//方法的返回值类型是被依赖的Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> Axe <span class="title">getAxe</span>(<span class="params"></span>)</span>;</span><br><span class="line">    @<span class="function">Override</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title">useAxe</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        System.<span class="keyword">out</span>.println(<span class="string">"正在使用"</span>+getAxe()+<span class="string">"砍柴!"</span>);</span><br><span class="line">        System.<span class="keyword">out</span>.println(getAxe().chop());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>bean.xml核心配置：<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=<span class="string">"chinese"</span> class=<span class="string">"com.bean.Chinese"</span>&gt;</span><br><span class="line">   &lt;lookup-<span class="keyword">method</span> name=<span class="string">"getAxe"</span> bean=<span class="string">"steelAxe"</span>/&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line">&lt;bean id=<span class="string">"steelAxe"</span> class=<span class="string">"com.bean.SteelAxe"</span> scope=<span class="string">"prototype"</span>/&gt;</span><br></pre></td></tr></table></figure></p>
<p>Test.java :<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public class Test &#123;</span><br><span class="line">    public static void main(String<span class="comment">[]</span> args) &#123;</span><br><span class="line">        ApplicationContext ctx=new ClassPathXmlApplicationContext(<span class="string">"bean.xml"</span>);</span><br><span class="line">        <span class="keyword">Person</span> p=(<span class="keyword">Person</span>) ctx.getBean(<span class="string">"chinese"</span>);</span><br><span class="line">        p.useAxe();</span><br><span class="line">        p.useAxe();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>我们在singleton Bean里新增一个抽象方法，该方法的返回值类型是被依赖的Bean，该方法是一个抽象方法，其实现由Spring完成。问题是：Spring怎么知道如何实现该方法呢？为了让Spring知道如何实现该方法，我们需要在配置文件中使用<code>&lt;lookup-method.../&gt;</code>元素来配置这个方法。<br>使用<code>&lt;lookup-method.../&gt;</code>元素需要指定如下两个属性：</p>
<ol>
<li>name：指定需要让Spring实现的方法。</li>
<li>bean：指定Spring实现该方法后的返回值。</li>
</ol>
<p>程序的执行结果表明：使用lookup方法注入后，系统每次调用getAxe( )方法都将生成一个新的SteelAxe实例，这就可以保证当singleton作用域的Bean需要全新的Bean实例时，直接调用getAxe()方法即可，从而可以避免一直使用最早注入的Bean实例。</p>
<h2 id="深入理解依赖关系配置">深入理解依赖关系配置</h2><p>组件与组件之间的耦合，采用依赖注入管理，但是普通的javabean属性值，应直接在代码里设置。</p>
<p>在spring配置文件中使用xml元素进行配置,实际上是让spring执行相应的java代码<br>例如:</p>
<ol>
<li>使用<bean>元素，就是让spring执行无参数构造函数</bean></li>
<li>使用<property> 就是让spring执行setter方法</property></li>
</ol>
<p>但是java程序还有可能还有其他语句,调用getting,调用普通方法,访问类或者对象的file,spring也为这种语句提供利配置的语法</p>
<ol>
<li>调用getter方法：使用 PropertyPathFactoryBean</li>
<li>访问类或对象的Field值，使用FieldRetrievingFactoryBean</li>
<li>调用普通方法，使用MethodInvokingFactoryBean</li>
</ol>
<p>由此可见，spring可以然我们不写java代码就可以实现java编程，只要使用合适XML 语法进行配置，spring就可通过反射执行任意的底层java代码。</p>
<h3 id="注入其他Bean的属性值">注入其他Bean的属性值</h3><p>属性值的注入，是通过PropertyPathFactoryBean完成的，PropertyPathFactoryBean用来获取目标bean的属性，获得的值可以注入到其他bean,也可以定义成新的bean</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"person"</span> <span class="attribute">class</span>=<span class="value">"com.bean.Person"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"age"</span> <span class="attribute">value</span>=<span class="value">"30"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"son"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">class</span>=<span class="value">"com.bean.Son"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"age"</span> <span class="attribute">value</span>=<span class="value">"11"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--如下将会将person的属性son的属性age传入son1实例的age属性--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"son1"</span> <span class="attribute">class</span>=<span class="value">"com.bean.Son"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"age"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--以下是访问bean属性的简单方式,这样可以将person这个bean的age属性赋值给son1这个bean的age属性--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"person.son.age"</span> <span class="attribute">class</span>=<span class="value">"org.springframework.beans.factory.config.PropertyPathFactoryBean"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- 以下将会获得结果son,它将是person bean的son的数值--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"son2"</span> <span class="attribute">class</span>=<span class="value">"org.springframework.beans.factory.config.PropertyPathFactoryBean"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"targetBeanName"</span> <span class="attribute">value</span>=<span class="value">"person"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"propertyPath"</span> <span class="attribute">value</span>=<span class="value">"son"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- 以下将会获得结果11,它将是person bean的son的age属性--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"theAge1"</span> <span class="attribute">class</span>=<span class="value">"org.springframework.beans.factory.config.PropertyPathFactoryBean"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"targetBeanName"</span> <span class="attribute">value</span>=<span class="value">"person"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"propertyPath"</span> <span class="attribute">value</span>=<span class="value">"son.age"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- 以下会获得结果为30 ,它将是获得该bean的内部bean的age属性--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"theAge2"</span> <span class="attribute">class</span>=<span class="value">"org.springframework.beans.factory.config.PropertyPathFactoryBean"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"targetObject"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">class</span>=<span class="value">"com.bean.Person"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"age"</span> <span class="attribute">value</span>=<span class="value">"30"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">property</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"propertyPath"</span> <span class="attribute">value</span>=<span class="value">"age"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>测试代码：</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public static void main<span class="params">(String[] args)</span> throws Exception &#123;</span><br><span class="line">        String path=new Test<span class="params">()</span>.getClass<span class="params">()</span>.getResource<span class="params">(<span class="string">"/"</span>)</span>.getPath<span class="params">()</span>;</span><br><span class="line">        String realpath=path.substring<span class="params">(<span class="number">1</span>, path.length<span class="params">()</span>)</span>;</span><br><span class="line">        ApplicationContext context=new FileSystemXmlApplicationContext<span class="params">(realpath+<span class="string">"/superIOCparam.xml"</span>)</span>;</span><br><span class="line">        Son son1=<span class="params">(Son)</span>context.getBean<span class="params">(<span class="string">"son1"</span>)</span>;</span><br><span class="line">        Son son2=<span class="params">(Son)</span>context.getBean<span class="params">(<span class="string">"son2"</span>)</span>;</span><br><span class="line"></span><br><span class="line">        System.out.println<span class="params">(<span class="string">"person age is:"</span>+son1.getAge<span class="params">()</span>)</span>;</span><br><span class="line">        System.out.println<span class="params">(<span class="string">"person age is:"</span>+son2.getAge<span class="params">()</span>)</span>;</span><br><span class="line">        System.out.println<span class="params">(context.getBean<span class="params">(<span class="string">"theAge1"</span>)</span>)</span>;</span><br><span class="line">        System.out.println<span class="params">(context.getBean<span class="params">(<span class="string">"theAge2"</span>)</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol>
<li>可以将Bean实例的属性值注入另一个Bean，此时bean的id是指定属性表达式，不是唯一标识。</li>
<li>可以将Bean实例的属性值直接定义成Bean实例，此时的id就是它的唯一标识。且必须指定两个属性：targetBeanName用于指定目标Bean，确定获取哪个Bean的属性值，或targetObject用于指定嵌套Bean实例；propertyPath，用于指定属性，确定获取目标Bean的哪个属性值，此处的属性可直接使用复合属性的形式。</li>
</ol>
<h3 id="注入其他Bean的Field值">注入其他Bean的Field值</h3><p>FieldRetrievingFactoryBean获得目标Bean的Field值后，得到的值可注入给其他Bean，也可直接定义成新的Bean。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 将指定的类的静态Field设置成bean的属性值 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"son"</span> <span class="attribute">class</span>=<span class="value">"com.bean.Son"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"age"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- id指定了哪个Field的值 将会被设置给id="son"的bean --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"java.sql.Connection.TRANSACTION_SERIALIZABLE"</span></span><br><span class="line">            <span class="attribute">class</span>=<span class="value">"org.springframework.beans.factory.config.FieldRetrievingFactoryBean"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- 将其他bean的Field定义成一个bean --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"theAge1"</span> <span class="attribute">class</span>=<span class="value">"org.springframework.beans.factory.config.FieldRetrievingFactoryBean"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- targetClass 设置Field所在的类,targetObject,当目标对象时使用(代替targetClass) --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"targetClass"</span> <span class="attribute">value</span>=<span class="value">"java.sql.Connection"</span> /&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- targetField指定目标类的目标Field --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"targetField"</span> <span class="attribute">value</span>=<span class="value">"TRANSACTION_SERIALIZABLE"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- 将静态Field定义成一个bean的简单写法 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"theAge2"</span> <span class="attribute">class</span>=<span class="value">"org.springframework.beans.factory.config.FieldRetrievingFactoryBean"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"staticField"</span> <span class="attribute">value</span>=<span class="value">"java.sql.Connection.TRANSACTION_SERIALIZABLE"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>测试代码：</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public static void main<span class="params">(String[] args)</span> throws Exception &#123;</span><br><span class="line">        String path=new Test<span class="params">()</span>.getClass<span class="params">()</span>.getResource<span class="params">(<span class="string">"/"</span>)</span>.getPath<span class="params">()</span>;</span><br><span class="line">        String realpath=path.substring<span class="params">(<span class="number">1</span>, path.length<span class="params">()</span>)</span>;</span><br><span class="line">        ApplicationContext context=new FileSystemXmlApplicationContext<span class="params">(realpath+<span class="string">"/superIOCparam.xml"</span>)</span>;</span><br><span class="line">        Son son=<span class="params">(Son)</span>context.getBean<span class="params">(<span class="string">"son"</span>,Son.class)</span>;</span><br><span class="line"></span><br><span class="line">        System.out.println<span class="params">(<span class="string">"son age is:"</span>+son.getAge<span class="params">()</span>)</span>;</span><br><span class="line">        System.out.println<span class="params">(context.getBean<span class="params">(<span class="string">"theAge1"</span>)</span>)</span>;</span><br><span class="line">        System.out.println<span class="params">(context.getBean<span class="params">(<span class="string">"theAge2"</span>)</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>使用FieldRetrievingFactoryBean获取Field值时，必须指定两个属性值</p>
<ul>
<li>targetClass或targetObject：分别用于指定Field值所在的目标类或目标对象，如果需要获得Field是静态Field，则使用targetClass指定目标类，否则使用targetObject指定目标对象。</li>
<li>targetField：用于指定目标Field的Field名。如果是静态Field可以通过staticField直接指定域。</li>
</ul>
<h3 id="注入其他Bean的方法返回值">注入其他Bean的方法返回值</h3><p>通过MethodInvokingFactoryBean工厂Bean，可获得指定方法的返回值并将其注入到指定Bean实例的指定属性，也可以直接定义成Bean实例。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 提供方法的bean --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"valueGenerator"</span> <span class="attribute">class</span>=<span class="value">"com.util.valueGenerator"</span> /&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 将一个bean的方法 返回值 注入 新bean的 age属性 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"son1"</span> <span class="attribute">class</span>=<span class="value">"com.bean.Son"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"age"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">class</span>=<span class="value">"org.springframework.beans.factory.config.MethodInvokingFactoryBean"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"targetObject"</span> <span class="attribute">ref</span>=<span class="value">"valueGenerator"</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"targetMethod"</span> <span class="attribute">value</span>=<span class="value">"getValue"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 上面 是调用非静态类对象的getValue()这种无参方法 --&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- 调用静态类的静态方法,静态方法的返回值直接 定义成bean --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"sysProps"</span> <span class="attribute">class</span>=<span class="value">"org.springframework.beans.factory.config.MethodInvokingFactoryBean"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"targetClass"</span> <span class="attribute">value</span>=<span class="value">"java.lang.System"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"targetMethod"</span> <span class="attribute">value</span>=<span class="value">"getProperties"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 调用无参 静态类的静态方法 创建bean name="staticMethod",value=静态类.静态方法--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"myBean"</span> <span class="attribute">class</span>=<span class="value">"org.springframework.beans.factory.config.MethodInvokingFactoryBean"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"staticMethod"</span> <span class="attribute">value</span>=<span class="value">"xxx.MyStaticClass.myStaticMethod"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- 有参数的方法调用,返回值 配置成一个bean --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"javaVersion"</span> <span class="attribute">class</span>=<span class="value">"org.springframework.beans.factory.config.MethodInvokingFactoryBean"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 目标bean,确定调用哪个bean的方法 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"targetObject"</span> <span class="attribute">ref</span>=<span class="value">"sysProps"</span> /&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 确定目标方法,确定调用bean的哪个方法 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"targetMethod"</span> <span class="attribute">value</span>=<span class="value">"getProperty"</span> /&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 确定调用目标方法的参数 相当于调用getProperty方法,传递参数"java.version" --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"arguments"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">list</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">value</span>&gt;</span>java.version<span class="tag">&lt;/<span class="title">value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">list</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>ValueGenrator类<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">ValueGenerator</span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getValue</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">2</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">getStaticValue</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">8</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>测试类<br><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public static void main<span class="params">(String[] args)</span> throws Exception &#123;</span><br><span class="line">        String path=new Test<span class="params">()</span>.getClass<span class="params">()</span>.getResource<span class="params">(<span class="string">"/"</span>)</span>.getPath<span class="params">()</span>;</span><br><span class="line">        String realpath=path.substring<span class="params">(<span class="number">1</span>, path.length<span class="params">()</span>)</span>;</span><br><span class="line">        ApplicationContext context=new FileSystemXmlApplicationContext<span class="params">(realpath+<span class="string">"/superIOCparam.xml"</span>)</span>;</span><br><span class="line">        Son son1=<span class="params">(Son)</span>context.getBean<span class="params">(<span class="string">"son1"</span>,Son.class)</span>;</span><br><span class="line">        Son son2=<span class="params">(Son)</span>context.getBean<span class="params">(<span class="string">"son2"</span>,Son.class)</span>;</span><br><span class="line"></span><br><span class="line">        System.out.println<span class="params">(<span class="string">"son age is:"</span>+son1.getAge<span class="params">()</span>)</span>;</span><br><span class="line">        System.out.println<span class="params">(<span class="string">"son age is:"</span>+son2.getAge<span class="params">()</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ul>
<li>targetClass或targetObject：分别用于指定目标类或目标对象。</li>
<li>targetMethod：用于指定目标方法的方法名。如果是静态方法可以通过staticMethod直接指定方法。</li>
</ul>
<h2 id="基于xml_schema_的简化配置方式">基于xml schema 的简化配置方式</h2><h3 id="使用p名称空间配置属性">使用p名称空间配置属性</h3><p>使用p命名空间可以简化原来property 的配置</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">beans</span> <span class="attribute">xmlns:xsi</span>=<span class="value">"http://www.w3.org/2001/XMLSchema-instance"</span></span><br><span class="line"><span class="attribute">xmlns</span>=<span class="value">"http://www.springframework.org/schema/beans"</span></span><br><span class="line"><span class="attribute">xmlns:p</span>=<span class="value">"http://www.springframework.org/schema/p"</span></span><br><span class="line"><span class="attribute">xsi:schemaLocation</span>=<span class="value">"http://www.springframework.org/schema/beans</span><br><span class="line">http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 配置Chinese实例 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"chinese"</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.Chinese"</span> <span class="attribute">p:age</span>=<span class="value">"29"</span> <span class="attribute">p:age-ref</span>=<span class="value">"stoneAxe"</span>/&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 配置stoneAxe实例 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"stoneAxe"</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.StoneAxe"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>首先，需要导入p名字空间，通过在axe后添加”-ref”指定该值不是一个具体的值，而是对另外一个Bean的引用。</p>
<h3 id="使用util_Schema">使用util Schema</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">beans</span> <span class="attribute">xmlns:xsi</span>=<span class="value">"http://www.w3.org/2001/XMLSchema-instance"</span></span><br><span class="line"><span class="attribute">xmlns</span>=<span class="value">"http://www.springframework.org/schema/beans"</span></span><br><span class="line"><span class="attribute">xmlns:p</span>=<span class="value">"http://www.springframework.org/schema/p"</span></span><br><span class="line"><span class="attribute">xmlns:util</span>=<span class="value">"http://www.springframework.org/schema/util"</span></span><br><span class="line"><span class="attribute">xsi:schemaLocation</span>=<span class="value">"http://www.springframework.org/schema/beans</span><br><span class="line">http://www.springframework.org/schema/util</span><br><span class="line">http://www.springframework.org/schema/util/spring-util-3.0.xsd</span><br><span class="line">http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 配置Chinese实例 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"chinese"</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.Chinese"</span></span><br><span class="line">    <span class="attribute">p:age-ref</span>=<span class="value">"chin.age"</span></span><br><span class="line">    <span class="attribute">p:age-ref</span>=<span class="value">"stoneAxe"</span></span><br><span class="line">    <span class="attribute">p:schools-ref</span>=<span class="value">"chin.schools"</span></span><br><span class="line">    <span class="attribute">p:axes-ref</span>=<span class="value">"chin.axes"</span></span><br><span class="line">    <span class="attribute">p:scores-ref</span>=<span class="value">"chin.scores"</span> /&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 配置stoneAxe实例 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"stoneAxe"</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.StoneAxe"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"steelAxe"</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.SteelAxe"</span> /&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 将指定类的静态Field暴露出来 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">util:constant</span> <span class="attribute">id</span>=<span class="value">"chin.age"</span> <span class="attribute">static-field</span>=<span class="value">"java.sql.Connection.TRANSACTION_SERIALIZABLE"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 将指定bean的属性 暴露出来 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">util:property-path</span> <span class="attribute">id</span>=<span class="value">"test"</span> <span class="attribute">path</span>=<span class="value">"chinese.age"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 加载指定资源文件 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">util:properties</span> <span class="attribute">id</span>=<span class="value">"confTest"</span> <span class="attribute">location</span>=<span class="value">"classpath:message_zh_CN.properties"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 定义一个list --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">util:list</span> <span class="attribute">id</span>=<span class="value">"chin.schools"</span> <span class="attribute">list-class</span>=<span class="value">"java.util.LinkedList"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">value</span>&gt;</span>小学<span class="tag">&lt;/<span class="title">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">value</span>&gt;</span>中学<span class="tag">&lt;/<span class="title">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">value</span>&gt;</span>大学<span class="tag">&lt;/<span class="title">value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">util:list</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 定义一个set对象 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">util:set</span> <span class="attribute">id</span>=<span class="value">"chin.axes"</span> <span class="attribute">set-class</span>=<span class="value">"java.util.HashSet"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">value</span>&gt;</span>字符串斧子<span class="tag">&lt;/<span class="title">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">bean</span> <span class="attribute">class</span>=<span class="value">"com.spring.service.impl.SteelAxe"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">ref</span> <span class="attribute">local</span>=<span class="value">"stoneAxe"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">util:set</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 定一个 map对象 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">util:map</span> <span class="attribute">id</span>=<span class="value">"chin.scores"</span> <span class="attribute">map-class</span>=<span class="value">"java.util.TreeMap"</span> <span class="attribute">key-type</span>=<span class="value">"java.lang.String"</span> <span class="attribute">value-type</span>=<span class="value">"java.lang.Double"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">entry</span> <span class="attribute">key</span>=<span class="value">"数学"</span> <span class="attribute">value</span>=<span class="value">"89"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">entry</span> <span class="attribute">key</span>=<span class="value">"英语"</span> <span class="attribute">value</span>=<span class="value">"89"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="title">entry</span> <span class="attribute">key</span>=<span class="value">"语文"</span> <span class="attribute">value</span>=<span class="value">"89"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">util:map</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>util Schema元素</p>
<ul>
<li>constant：该标签用于将指定类的静态Field暴露成一个Bean实例。使用该标签时可制定如下两个属性。<ul>
<li>id：该属性指定将静态Field定义成名为id的Bean实例</li>
<li>static-field：该属性指定将哪个类、哪个静态Field暴露出来。</li>
</ul>
</li>
<li>property-path：该标签用于将指定Bean实例的指定属性暴露成一个Bean实例，使用该标签时可指定如下两个属性<ul>
<li>id：该属性指定将属性定义成名为id的Bean实例</li>
<li>path：该属性指定将哪个Bean实例、哪个属性（支持复合属性）暴露出来。</li>
</ul>
</li>
<li>list 该标签用于定义一个List Bean，支持使用value、ref、bean等标签来定义List集合元素，使用该标签支持如下三个属性，<ul>
<li>id：该属性指定定义一个名为id的List实例</li>
<li>list-class：该属性指定Spring使用哪个List实现类来创建Bean实例</li>
<li>scope：指定该List实例的作用域</li>
</ul>
</li>
<li>set：该标签用于定义一个Set Bean，支持使用value、ref、bean等标签来定义Set集合元素，使用该标签支持如下三个属性。<ul>
<li>id：该属性指定定义一个名为id的Set Bean实例</li>
<li>set-class：该属性指定Set Bean使用哪个Set实现类来创建Bean实例</li>
<li>scope：指定该Set Bean实例的作用域</li>
</ul>
</li>
<li>map 该标签用于定义一个Map Bean，支持使用entry来定义Map的key-value对．使用该标签支持如下三个属性<ul>
<li>id：该属性指定定义一个名为id的Map Bean实例</li>
<li>map-class：该属性指定Spring使用哪个Map实现类来创建Bean实例</li>
<li>scope：指定该Map Bean实例的作用域</li>
</ul>
</li>
<li>properties：该标签用于加载一份资源文件并根据加载的资源文件创建个Properties Bean实例，使用该标签可指定如下几个属性<ul>
<li>id：该属性指定定义一个名为id的Properties Bean实例</li>
<li>location：指定资源文件的位置。</li>
<li>scope：指定该Properties Bean实例的作用域</li>
</ul>
</li>
</ul>
<h2 id="Spring3-0提供的表达式语言(SpEl)">Spring3.0提供的表达式语言(SpEl)</h2><p>Spring的表达式语言与Java注解结合，以便开发人员可以撰写和指向他们的配置，而不需要单独的XML文件写入，使得Spring开发者在不需要XML的情况下对应用进行配置。</p>
<h3 id="使用Expression接口进行表达式求值">使用Expression接口进行表达式求值</h3><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">public class SpELTest &#123;</span><br><span class="line">    @Test</span><br><span class="line">    public void test2<span class="params">()</span> &#123;</span><br><span class="line">        ExpressionParser parser=new SpelExpressionParser<span class="params">()</span>;</span><br><span class="line">        Expression <span class="built_in">exp</span>=parser.parseExpression<span class="params">(<span class="string">"'Hello World'"</span>)</span>;</span><br><span class="line">        System.out.println<span class="params">(<span class="string">"Hello World的结果"</span>+exp.getValue<span class="params">()</span>)</span>;</span><br><span class="line"></span><br><span class="line">        <span class="built_in">exp</span>=parser.parseExpression<span class="params">(<span class="string">"'Hello World'.concat('!')"</span>)</span>;</span><br><span class="line">        System.out.println<span class="params">(<span class="string">"concat后的结果"</span>+exp.getValue<span class="params">()</span>)</span>;</span><br><span class="line"></span><br><span class="line">        <span class="built_in">exp</span>=parser.parseExpression<span class="params">(<span class="string">"'Hello World'.bytes"</span>)</span>;</span><br><span class="line">        System.out.println<span class="params">(<span class="string">"调用getBytes方法后的结果"</span>+exp.getValue<span class="params">()</span>)</span>;</span><br><span class="line"></span><br><span class="line">        <span class="built_in">exp</span>=parser.parseExpression<span class="params">(<span class="string">"'Hello World'.bytes.length"</span>)</span>;</span><br><span class="line">        System.out.println<span class="params">(<span class="string">"方法返回值后的属性的结果"</span>+exp.getValue<span class="params">()</span>)</span>;</span><br><span class="line"></span><br><span class="line">        <span class="built_in">exp</span>=parser.parseExpression<span class="params">(<span class="string">"new String('Hello World').toUpperCase()"</span>)</span>;</span><br><span class="line">        <span class="built_in">exp</span>=parser.parseExpression<span class="params">(<span class="string">"age"</span>)</span>;</span><br><span class="line">        Chinese c=act.getBean<span class="params">(<span class="string">"chinese"</span>,Chinese.class)</span>;</span><br><span class="line">        System.out.println<span class="params">(<span class="string">"以Chinese为root,age的表达式的值是:"</span>+exp.getValue<span class="params">(c, Integer.class)</span>)</span>;</span><br><span class="line">        <span class="built_in">exp</span>=parser.parseExpression<span class="params">(<span class="string">"age==15"</span>)</span>;</span><br><span class="line">        StandardEvaluationContext ctx=new StandardEvaluationContext<span class="params">()</span>;</span><br><span class="line">        ctx.setRootObject<span class="params">(c)</span>;</span><br><span class="line">        System.out.println<span class="params">(exp.getValue<span class="params">(ctx, Boolean.class)</span>)</span>;</span><br><span class="line"></span><br><span class="line">        List&lt;Boolean&gt; list=new ArrayList&lt;Boolean&gt;<span class="params">()</span>;</span><br><span class="line">        list.add<span class="params">(<span class="literal">true</span>)</span>;</span><br><span class="line">        EvaluationContext ctx2=new StandardEvaluationContext<span class="params">()</span>;</span><br><span class="line">        ctx2.setVariable<span class="params">(<span class="string">"list"</span>,list)</span>;</span><br><span class="line"></span><br><span class="line">        parser.parseExpression<span class="params">(<span class="string">"#list[0]"</span>)</span>.setValue<span class="params">(ctx2, <span class="string">"false"</span>)</span>;</span><br><span class="line">        System.out.println<span class="params">(<span class="string">"List集合中的第一个元素:"</span>+list.get<span class="params">(<span class="number">0</span>)</span>)</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol>
<li>创建解析器：SpEL使用ExpressionParser接口表示解析器，提供SpelExpressionParser默认实现；</li>
<li>解析表达式：使用ExpressionParser的parseExpression来解析相应的表达式为Expression对象。</li>
<li>构造上下文：准备比如变量定义等等表达式需要的上下文数据。</li>
<li>求值：通过Expression接口的getValue方法根据上下文获得表达式值。</li>
</ol>
<p>接下来让我们看下SpEL的主要接口吧：</p>
<ol>
<li>ExpressionParser接口：表示解析器，默认实现是org.springframework.expression.spel.standard包中的SpelExpressionParser类，使用parseExpression方法将字符串表达式转换为Expression对象，对于ParserContext接口用于定义字符串表达式是不是模板，及模板开始与结束字符</li>
<li>EvaluationContext接口：表示上下文环境，默认实现是org.springframework.expression.spel.support包中的StandardEvaluationContext类，使用setRootObject方法来设置根对象，使用setVariable方法来注册自定义变量，使用registerFunction来注册自定义函数等等。</li>
<li>Expression接口：表示表达式对象，默认实现是org.springframework.expression.spel.standard包中的SpelExpression，提供getValue方法用于获取表达式值，提供setValue方法用于设置对象值。</li>
</ol>
<h3 id="Bean定义中的表达式语言支持">Bean定义中的表达式语言支持</h3><p>xml配置文件和Annotation中使用SpEL时，都需要在表达式外面增加#{}包围。</p>
<h3 id="SpEL语法详述">SpEL语法详述</h3><h4 id="基本表达式">基本表达式</h4><ul>
<li>字面量表达式</li>
<li>算术运算表达式</li>
<li>比较运算表达式</li>
<li>逻辑运算表达式</li>
<li>字符串连接与截取表达式</li>
<li>三目运算及Elivis运算表达式</li>
<li>正则表达式</li>
</ul>
<p>字面量表达式<br>字符串、数字类型（int、long、float、double）、布尔类型、null。<br>字符串 ‘Hello World!’、”Hello World!”<br>数值类型 1、-1L、1.1、1.1E+2、0xa、0xaL<br>布尔类型 true、false<br>null null</p>
<p>算术运算表达式<br>加(+)、减(-)、乘(<code>*</code>)、除(/或DIV)、求余（%或MOD）、幂（^）。<br>加减乘除 <code>1+2-3*4/2</code>、<code>1+2-3*4DIV2</code><br>求余 <code>4%3</code>、<code>4MOD 3</code><br>幂运算 <code>2^3</code></p>
<p>比较运算表达式</p>
<p>不等于 !=或ne 1!= 1或 1ne 1<br>等于 ==或eq 1== 1或 1eq 1<br>大于等于 &gt;=或ge 1&gt;= 1或 1ge 1<br>小于等于 &lt;=或le 1&lt;= 1或 1le 1<br>大于 &gt;或gt 1&gt; 1或 1gt 1<br>小于 &lt;或lt 1&lt; 1或 1lt 1<br>区间 between 1 between {1, 2}</p>
<p>逻辑运算表达式<br>与 AND true AND true<br>或 OR true OR true<br>非 NOT NOT true</p>
<p>字符串连接及截取表达式<br>连接 + ‘Hello’ + ‘World !’<br>截取一个字符 string[index] ‘Hello World’[0]</p>
<p>三目运算及Elivis运算表达式<br>三目运算符 表达式1?表达式2:表达式3 2&gt;1?true:false<br>Elivis运算 表达式1?:表达式2 null? :false或true?:false</p>
<p>正则表达式<br>正则表达式 matches ‘123’ matches ‘\d{3}’</p>
<h4 id="类相关表达式">类相关表达式</h4><ul>
<li>类类型表达式</li>
<li>类实例化表达式</li>
<li>instanceof表达式</li>
<li>变量定义及引用</li>
<li>自定义函数</li>
<li>赋值表达式</li>
<li>对象属性存取及安全导航表达式<ul>
<li>访问root对象属性</li>
<li>安全访问</li>
<li>给root对象属性赋值</li>
</ul>
</li>
<li>对象方法调用</li>
<li>Bean引用</li>
</ul>
<p>类类型表达式</p>
<p>使用”T(Type)”来表示java.lang.Class实例，”Type”必须是类全限定名（java.lang包除外）。使用类类型表达式还可以进行访问类静态方法及类静态字段。</p>
<table>
<thead>
<tr>
<th>实例</th>
<th>示例</th>
</tr>
</thead>
<tbody>
<tr>
<td>java.lang包类访问</td>
<td>T(String)</td>
</tr>
<tr>
<td>其他包的类访问</td>
<td>T(foo.bar.spel.SpELTest)</td>
</tr>
<tr>
<td>类静态字段访问</td>
<td>T(Integer).MAX_VALUE</td>
</tr>
<tr>
<td>类静态方法调用</td>
<td>T(Integer).parseInt(‘1’)</td>
</tr>
</tbody>
</table>
<p>类实例化表达式</p>
<table>
<thead>
<tr>
<th>实例</th>
<th>示例</th>
</tr>
</thead>
<tbody>
<tr>
<td>java.lang包类的实例化</td>
<td>new String(‘hello’)</td>
</tr>
<tr>
<td>其他包的类实例化</td>
<td>new java.util.Date()</td>
</tr>
</tbody>
</table>
<p>instanceof</p>
<table>
<thead>
<tr>
<th>实例</th>
<th>示例</th>
</tr>
</thead>
<tbody>
<tr>
<td>Java内使用同义</td>
<td>‘hello’ instanceof T(String)</td>
</tr>
</tbody>
</table>
<p>变量定义与引用</p>
<p>变量定义通过EvaluationContext接口的setVariable(variableName, value)方法定义；在表达式中使用“#variableName”引用；除了引用自定义变量，SpEL还允许引用根对象及当前上下文对象，使用 “#root”引用根对象，使用“#this”引用当前上下文对象。“#this”引用当前上下文对象，此处“#this”即根对象。</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">publicvoid testVariableExpression<span class="params">()</span> &#123;</span><br><span class="line">   ExpressionParser parser =new SpelExpressionParser<span class="params">()</span>;</span><br><span class="line">   EvaluationContext context =new StandardEvaluationContext<span class="params">()</span>;</span><br><span class="line">   context.setVariable<span class="params">(<span class="string">"variable"</span>,<span class="string">"hello"</span>)</span>;</span><br><span class="line">   context.setVariable<span class="params">(<span class="string">"variable"</span>,<span class="string">"world"</span>)</span>;</span><br><span class="line"></span><br><span class="line">   String result1 = parser.parseExpression<span class="params">(<span class="string">"#variable"</span>)</span>.getValue<span class="params">(context, String.class)</span>;</span><br><span class="line">   Assert.assertEquals<span class="params">(<span class="string">"world"</span>, result1)</span>;</span><br><span class="line"></span><br><span class="line">   context =new StandardEvaluationContext<span class="params">(<span class="string">"hello"</span>)</span>;</span><br><span class="line">   String result2 = parser.parseExpression<span class="params">(<span class="string">"#root"</span>)</span>.getValue<span class="params">(context, String.class)</span>;</span><br><span class="line">   Assert.assertEquals<span class="params">(<span class="string">"hello"</span>, result2)</span>;</span><br><span class="line"></span><br><span class="line">   String result3 = parser.parseExpression<span class="params">(<span class="string">"#this"</span>)</span>.getValue<span class="params">(context, String.class)</span>;</span><br><span class="line">   Assert.assertEquals<span class="params">(<span class="string">"hello"</span>, result3)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>自定义函数</p>
<p>目前只支持类静态方法注册为自定义函数；SpEL使用StandardEvaluationContext的registerFunction方法进行注册自定义函数，其实完全可以使用setVariable代替，两者其实本质是一样的。<br><figure class="highlight ocaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">@<span class="type">Test</span></span><br><span class="line">publicvoid testFunctionExpression<span class="literal">()</span>throws <span class="type">SecurityException</span>, <span class="type">NoSuchMethodException</span> &#123;</span><br><span class="line">    <span class="type">ExpressionParser</span> <span class="keyword">parser</span> = <span class="keyword">new</span> <span class="type">SpelExpressionParser</span><span class="literal">()</span>;</span><br><span class="line">    <span class="type">StandardEvaluationContext</span> context = <span class="keyword">new</span> <span class="type">StandardEvaluationContext</span><span class="literal">()</span>;</span><br><span class="line">    <span class="type">Method</span> parseInt = <span class="type">Integer</span>.<span class="keyword">class</span>.getDeclaredMethod(<span class="string">"parseInt"</span>, <span class="type">String</span>.<span class="keyword">class</span>);</span><br><span class="line">    context.registerFunction(<span class="string">"parseInt"</span>, parseInt);</span><br><span class="line">    context.setVariable(<span class="string">"parseInt2"</span>, parseInt);</span><br><span class="line">    <span class="type">String</span> expression1 = <span class="string">"#parseInt('3') == #parseInt2('3')"</span>;</span><br><span class="line">    boolean result1 = <span class="keyword">parser</span>.parseExpression(expression1).getValue(context,boolean.<span class="keyword">class</span>);</span><br><span class="line">    <span class="type">Assert</span>.assertEquals(<span class="literal">true</span>, result1);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>赋值表达式</p>
<p>SpEL即允许给自定义变量赋值，也允许给跟对象赋值，直接使用“#variableName=value”即可赋值：<br><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">publicvoid testAssignExpression<span class="params">()</span> &#123;</span><br><span class="line">    ExpressionParser parser = new SpelExpressionParser<span class="params">()</span>;</span><br><span class="line">    <span class="comment">// 1.给root对象赋值</span></span><br><span class="line">    EvaluationContext context = new StandardEvaluationContext<span class="params">(<span class="string">"aaaa"</span>)</span>;</span><br><span class="line">    String result1 = parser.parseExpression<span class="params">(<span class="string">"#root='aaaaa'"</span>)</span>.getValue<span class="params">(context, String.class)</span>;</span><br><span class="line">    Assert.assertEquals<span class="params">(<span class="string">"aaaaa"</span>, result1)</span>;</span><br><span class="line">    String result2 = parser.parseExpression<span class="params">(<span class="string">"#this='aaaa'"</span>)</span>.getValue<span class="params">(context, String.class)</span>;</span><br><span class="line">    Assert.assertEquals<span class="params">(<span class="string">"aaaa"</span>, result2)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 2.给自定义变量赋值</span></span><br><span class="line">    context.setVariable<span class="params">(<span class="string">"#variable"</span>,<span class="string">"variable"</span>)</span>;</span><br><span class="line">    String result3 = parser.parseExpression<span class="params">(<span class="string">"#variable=#root"</span>)</span>.getValue<span class="params">(context, String.class)</span>;</span><br><span class="line">    Assert.assertEquals<span class="params">(<span class="string">"aaaa"</span>, result3)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>对象属性存取及安全导航表达式</p>
<p>对象属性获取非常简单，即使用如“a.property.property”这种点缀式获取，SpEL对于属性名首字母是不区分大小写的。</p>
<p>给对象属性赋值可以采用赋值表达式或Expression接口的setValue方法赋值，而且也可以采用点缀方式赋值。</p>
<p>SpEL还引入了Groovy语言中的安全导航运算符“(对象|属性)?.属性”，用来避免当“?.”前边的表达式为null时抛出空指针异常，而是返回null。<br><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">ExpressionParser parser =new SpelExpressionParser<span class="params">()</span>;</span><br><span class="line"><span class="comment">// ===============访问root对象属性 ===============</span></span><br><span class="line">Date date =new Date<span class="params">()</span>;</span><br><span class="line">StandardEvaluationContext context =new StandardEvaluationContext<span class="params">(date)</span>;</span><br><span class="line">int result1 = parser.parseExpression<span class="params">(<span class="string">"Year"</span>)</span>.getValue<span class="params">(context,int.class)</span>;</span><br><span class="line">Assert.assertEquals<span class="params">(date.getYear<span class="params">()</span>, result1)</span>;</span><br><span class="line">int result2 = parser.parseExpression<span class="params">(<span class="string">"year"</span>)</span>.getValue<span class="params">(context,int.class)</span>;</span><br><span class="line">Assert.assertEquals<span class="params">(date.getYear<span class="params">()</span>, result2)</span>;</span><br><span class="line"><span class="comment">// ===============安全访问 ===============</span></span><br><span class="line">context.setRootObject<span class="params">(null)</span>;</span><br><span class="line">Object result3 = parser.parseExpression<span class="params">(<span class="string">"#root?.year"</span>)</span>.getValue<span class="params">(context, Object.class)</span>;</span><br><span class="line">Assert.assertEquals<span class="params">(null, result3)</span>;</span><br><span class="line"><span class="comment">// ===============给root对象属性赋值 ===============</span></span><br><span class="line">context.setRootObject<span class="params">(date)</span>;</span><br><span class="line">int result4 = parser.parseExpression<span class="params">(<span class="string">"Year = 4"</span>)</span>.getValue<span class="params">(context,int.class)</span>;</span><br><span class="line">Assert.assertEquals<span class="params">(<span class="number">4</span>, result4)</span>;</span><br><span class="line">parser.parseExpression<span class="params">(<span class="string">"Year"</span>)</span>.setValue<span class="params">(context, <span class="number">5</span>)</span>;</span><br><span class="line">int result5 = parser.parseExpression<span class="params">(<span class="string">"Year"</span>)</span>.getValue<span class="params">(context,int.class)</span>;</span><br><span class="line">Assert.assertEquals<span class="params">(<span class="number">5</span>, result5)</span>;</span><br></pre></td></tr></table></figure></p>
<p>对象方法调用</p>
<p>对象方法调用更简单，跟Java语法一样；如“’helo’.substring(2,4)”将返回“lo”。对于根对象可以直接调用方法。</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">ExpressionParser parser <span class="subst">=</span><span class="literal">new</span> SpelExpressionParser();</span><br><span class="line"><span class="comment">// ===============直接调用对象方法 ===============</span></span><br><span class="line"><span class="built_in">String</span> result1 <span class="subst">=</span> parser<span class="built_in">.</span>parseExpression(<span class="string">"'hello'.substring(3)"</span>)<span class="built_in">.</span>getValue(<span class="built_in">String</span><span class="built_in">.</span>class);</span><br><span class="line">Assert<span class="built_in">.</span>assertEquals(<span class="string">"lo"</span>, result1);</span><br><span class="line"><span class="comment">// ===============调用上下文root对象方法 ===============</span></span><br><span class="line"><span class="built_in">Date</span> <span class="built_in">date</span> <span class="subst">=</span><span class="literal">new</span> <span class="built_in">Date</span>();</span><br><span class="line">StandardEvaluationContext context <span class="subst">=</span><span class="literal">new</span> StandardEvaluationContext(<span class="built_in">date</span>);</span><br><span class="line">int result2 <span class="subst">=</span> parser<span class="built_in">.</span>parseExpression(<span class="string">"getYear()"</span>)<span class="built_in">.</span>getValue(context,int<span class="built_in">.</span>class);</span><br><span class="line">Assert<span class="built_in">.</span>assertEquals(<span class="built_in">date</span><span class="built_in">.</span>getYear(), result2);</span><br></pre></td></tr></table></figure>
<p>Bean引用</p>
<p>SpEL支持使用“@”符号来引用Bean，在引用Bean时需要使用BeanResolver接口实现来查找Bean，Spring提供BeanFactoryResolver实现。</p>
<p>在示例中首先初始化了一个IoC容器，ClassPathXmlApplicationContext 实现默认会把“System.getProperties()”注册为“systemProperties”Bean，因此使用 “@systemProperties”来引用该Bean。</p>
<figure class="highlight ocaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">@<span class="type">Test</span></span><br><span class="line">publicvoid testBeanExpression<span class="literal">()</span> &#123;</span><br><span class="line">   <span class="type">ClassPathXmlApplicationContext</span> ctx =<span class="keyword">new</span> <span class="type">ClassPathXmlApplicationContext</span><span class="literal">()</span>;</span><br><span class="line">    ctx.refresh<span class="literal">()</span>;</span><br><span class="line">   <span class="type">ExpressionParser</span> <span class="keyword">parser</span> =<span class="keyword">new</span> <span class="type">SpelExpressionParser</span><span class="literal">()</span>;</span><br><span class="line">   <span class="type">StandardEvaluationContext</span> context =<span class="keyword">new</span> <span class="type">StandardEvaluationContext</span><span class="literal">()</span>;</span><br><span class="line">   context.setBeanResolver(<span class="keyword">new</span> <span class="type">BeanFactoryResolver</span>(ctx));</span><br><span class="line">   <span class="type">Properties</span> result1 = <span class="keyword">parser</span>.parseExpression(<span class="string">"@systemProperties"</span>).getValue(context, <span class="type">Properties</span>.<span class="keyword">class</span>);</span><br><span class="line">    <span class="type">Assert</span>.assertEquals(<span class="type">System</span>.getProperties<span class="literal">()</span>, result1);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="集合相关表达式">集合相关表达式</h4><ul>
<li>内联List</li>
<li>内联Array</li>
<li>Collection，Map元素访问</li>
<li>Collection、Map、Array元素修改</li>
<li>集合投影</li>
<li>集合选择</li>
</ul>
<p>内联List</p>
<p>从Spring3.0.4开始支持内联List，使用{表达式，……}定义内联List。如“{1,2,3}”将返回一个整型的ArrayList，而“{}”将返回空的List，对于字面量表达式列表，SpEL会使用java.util.Collections.unmodifiableList方法将列表设置为不可修改。</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//将返回不可修改的空List</span></span><br><span class="line"><span class="built_in">List</span>&lt;Integer&gt; result2 = parser.parseExpression(<span class="string">"&#123;&#125;"</span>).getValue(<span class="built_in">List</span>.<span class="keyword">class</span>);</span><br><span class="line"><span class="comment">//对于列表中只要有一个不是字面量表达式，将只返回原始List，不会进行不可修改处理</span></span><br><span class="line"><span class="built_in">String</span> expression3 = <span class="string">"&#123; &#123;1 + 2,2 + 4&#125;, &#123;3, 4 + 4&#125; &#125;"</span>;</span><br><span class="line"><span class="built_in">List</span>&lt;<span class="built_in">List</span>&lt;Integer&gt;&gt; result3 = parser.parseExpression(expression3).getValue(<span class="built_in">List</span>.<span class="keyword">class</span>);</span><br><span class="line">result3.<span class="literal">get</span>(<span class="number">0</span>).<span class="literal">set</span>(<span class="number">0</span>, <span class="number">1</span>);</span><br><span class="line">Assert.assertEquals(<span class="number">2</span>, result3.size());</span><br></pre></td></tr></table></figure>
<p>内联Array</p>
<figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">//声明一维数组并初始化值</span><br><span class="line">int[] result2 = parser.parseExpression("new int[]&#123;1,2&#125;").getValue(int[].class);</span><br><span class="line">Assert.assertEquals(result2[0], 1);</span><br><span class="line">//定义多维数组但不初始化（定义多维数组不能初始化）</span><br><span class="line">int[<span class="link_label"></span>][<span class="link_reference"></span>][<span class="link_label"></span>] result3 = parser.parseExpression("new int[<span class="link_label">2</span>][<span class="link_reference">2</span>][<span class="link_label">2</span>]").getValue(int[<span class="link_label"></span>][<span class="link_reference"></span>][<span class="link_label"></span>].class);</span><br></pre></td></tr></table></figure>
<p>集合，字典元素访问</p>
<p>SpEL目前支持所有集合类型和字典类型的元素访问，使用“集合[索引]”访问集合元素，使用“map[key]”访问字典元素。<br>集合元素访问是通过Iterator遍历来定位元素位置的。<br><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// SpEL内联List访问</span></span><br><span class="line">int result1 = parser.parseExpression<span class="params">(<span class="string">"&#123;1,2,3&#125;[0]"</span>)</span>.getValue<span class="params">(int.class)</span>;</span><br><span class="line"><span class="comment">//即list.get(0)</span></span><br><span class="line">Assert.assertEquals<span class="params">(<span class="number">1</span>, result1)</span>;</span><br><span class="line"><span class="comment">// SpEL目前支持所有集合类型的访问</span></span><br><span class="line">Collection&lt;Integer&gt; collection =new HashSet&lt;Integer&gt;<span class="params">()</span>;</span><br><span class="line">collection.add<span class="params">(<span class="number">1</span>)</span>;</span><br><span class="line">collection.add<span class="params">(<span class="number">2</span>)</span>;</span><br><span class="line">EvaluationContext context2 =new StandardEvaluationContext<span class="params">()</span>;</span><br><span class="line">context2.setVariable<span class="params">(<span class="string">"collection"</span>, collection)</span>;</span><br><span class="line">int result2 = parser.parseExpression<span class="params">(<span class="string">"#collection[1]"</span>)</span>.getValue<span class="params">(context2,int.class)</span>;</span><br><span class="line"><span class="comment">//对于任何集合类型通过Iterator来定位元素</span></span><br><span class="line">Assert.assertEquals<span class="params">(<span class="number">2</span>, result2)</span>;</span><br><span class="line"><span class="comment">// SpEL对Map字典元素访问的支持</span></span><br><span class="line">Map&lt;String, Integer&gt; map =new HashMap&lt;String, Integer&gt;<span class="params">()</span>;</span><br><span class="line">map.put<span class="params">(<span class="string">"a"</span>, <span class="number">1</span>)</span>;</span><br><span class="line">EvaluationContext context3 =new StandardEvaluationContext<span class="params">()</span>;</span><br><span class="line">context3.setVariable<span class="params">(<span class="string">"map"</span>, map)</span>;</span><br><span class="line">int result3 = parser.parseExpression<span class="params">(<span class="string">"#map['a']"</span>)</span>.getValue<span class="params">(context3,int.class)</span>;</span><br><span class="line">Assert.assertEquals<span class="params">(<span class="number">1</span>, result3)</span>;</span><br></pre></td></tr></table></figure></p>
<p>列表，字典，数组元素修改</p>
<p>可以使用赋值表达式或Expression接口的setValue方法修改。对数组修改直接对“#array[index]”赋值即可修改元素值，同理适用于集合和字典类型。<br><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ===============修改数组元素值 ===============</span></span><br><span class="line">int[] array =newint[] &#123; <span class="number">1</span>, <span class="number">2</span> &#125;;</span><br><span class="line">EvaluationContext context1 =new StandardEvaluationContext<span class="params">()</span>;</span><br><span class="line">context1.setVariable<span class="params">(<span class="string">"array"</span>, array)</span>;</span><br><span class="line">int result1 = parser.parseExpression<span class="params">(<span class="string">"#array[1] = 3"</span>)</span>.getValue<span class="params">(context1,int.class)</span>;</span><br><span class="line">Assert.assertEquals<span class="params">(<span class="number">3</span>, result1)</span>;</span><br><span class="line"><span class="comment">// ===============修改集合值 ===============</span></span><br><span class="line">Collection&lt;Integer&gt; collection =new ArrayList&lt;Integer&gt;<span class="params">()</span>;</span><br><span class="line">collection.add<span class="params">(<span class="number">1</span>)</span>;</span><br><span class="line">collection.add<span class="params">(<span class="number">2</span>)</span>;</span><br><span class="line">EvaluationContext context2 =new StandardEvaluationContext<span class="params">()</span>;</span><br><span class="line">context2.setVariable<span class="params">(<span class="string">"collection"</span>, collection)</span>;</span><br><span class="line">int result2 = parser.parseExpression<span class="params">(<span class="string">"#collection[1] = 3"</span>)</span>.getValue<span class="params">(context2,int.class)</span>;</span><br><span class="line">Assert.assertEquals<span class="params">(<span class="number">3</span>, result2)</span>;</span><br><span class="line">parser.parseExpression<span class="params">(<span class="string">"#collection[1]"</span>)</span>.setValue<span class="params">(context2, <span class="number">4</span>)</span>;</span><br><span class="line">result2 = parser.parseExpression<span class="params">(<span class="string">"#collection[1]"</span>)</span>.getValue<span class="params">(context2,int.class)</span>;</span><br><span class="line">Assert.assertEquals<span class="params">(<span class="number">4</span>, result2)</span>;</span><br><span class="line"><span class="comment">// ===============修改map元素值 ===============</span></span><br><span class="line">Map&lt;String, Integer&gt; map =new HashMap&lt;String, Integer&gt;<span class="params">()</span>;</span><br><span class="line">map.put<span class="params">(<span class="string">"a"</span>, <span class="number">1</span>)</span>;</span><br><span class="line">EvaluationContext context3 =new StandardEvaluationContext<span class="params">()</span>;</span><br><span class="line">context3.setVariable<span class="params">(<span class="string">"map"</span>, map)</span>;</span><br><span class="line">int result3 = parser.parseExpression<span class="params">(<span class="string">"#map['a'] = 2"</span>)</span>.getValue<span class="params">(context3,int.class)</span>;</span><br><span class="line">Assert.assertEquals<span class="params">(<span class="number">2</span>, result3)</span>;</span><br></pre></td></tr></table></figure></p>
<p>集合投影</p>
<p>在SQL中投影指从表中选择出列，而在SpEL指根据集合中的元素中通过选择来构造另一个集合，该集合和原集合具有相同数量的元素；SpEL使用“（list|map）.![投影表达式]”来进行投影运算：<br><figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">Collection<span class="subst">&lt;</span><span class="built_in">Integer</span><span class="subst">&gt;</span> collection <span class="subst">=</span><span class="literal">new</span> ArrayList<span class="subst">&lt;</span><span class="built_in">Integer</span><span class="subst">&gt;</span>();</span><br><span class="line">collection<span class="built_in">.</span>add(<span class="number">4</span>);</span><br><span class="line">collection<span class="built_in">.</span>add(<span class="number">5</span>);</span><br><span class="line"><span class="comment">// =============== 测试集合或数组 ===============</span></span><br><span class="line">EvaluationContext context1 <span class="subst">=</span><span class="literal">new</span> StandardEvaluationContext();</span><br><span class="line">context1<span class="built_in">.</span>setVariable(<span class="string">"collection"</span>, collection);</span><br><span class="line">Collection<span class="subst">&lt;</span><span class="built_in">Integer</span><span class="subst">&gt;</span> result1 <span class="subst">=</span> parser<span class="built_in">.</span>parseExpression(<span class="string">"#collection.![#this+1]"</span>)<span class="built_in">.</span>getValue(context1, Collection<span class="built_in">.</span>class);</span><br><span class="line">Assert<span class="built_in">.</span>assertEquals(<span class="number">2</span>, result1<span class="built_in">.</span>size());</span><br><span class="line">Assert<span class="built_in">.</span>assertEquals(<span class="literal">new</span> <span class="built_in">Integer</span>(<span class="number">5</span>), result1<span class="built_in">.</span>iterator()<span class="built_in">.</span>next());</span><br><span class="line">对于集合或数组使用如上表达式进行投影运算，其中投影表达式中“<span class="variable">#this</span>”代表每个集合或数组元素，可以使用比如“<span class="variable">#this.property</span>”来获取集合元素的属性，其中“<span class="variable">#this</span>”可以省略。</span><br><span class="line"><span class="built_in">Map</span><span class="subst">&lt;</span><span class="built_in">String</span>, <span class="built_in">Integer</span><span class="subst">&gt;</span> <span class="built_in">map</span> <span class="subst">=</span><span class="literal">new</span> HashMap<span class="subst">&lt;</span><span class="built_in">String</span>, <span class="built_in">Integer</span><span class="subst">&gt;</span>();</span><br><span class="line"><span class="built_in">map</span><span class="built_in">.</span>put(<span class="string">"a"</span>, <span class="number">1</span>);</span><br><span class="line"><span class="built_in">map</span><span class="built_in">.</span>put(<span class="string">"b"</span>, <span class="number">2</span>);</span><br><span class="line"><span class="comment">// ===============测试Map ===============</span></span><br><span class="line">EvaluationContext context2 <span class="subst">=</span><span class="literal">new</span> StandardEvaluationContext();</span><br><span class="line">context2<span class="built_in">.</span>setVariable(<span class="string">"map"</span>, <span class="built_in">map</span>);</span><br><span class="line"><span class="built_in">List</span><span class="subst">&lt;</span><span class="built_in">Integer</span><span class="subst">&gt;</span> result2 <span class="subst">=</span></span><br><span class="line">parser<span class="built_in">.</span>parseExpression(<span class="string">"#map.![value+1]"</span>)<span class="built_in">.</span>getValue(context2, <span class="built_in">List</span><span class="built_in">.</span>class);</span><br><span class="line">Assert<span class="built_in">.</span>assertEquals(<span class="number">2</span>, result2<span class="built_in">.</span>size());</span><br></pre></td></tr></table></figure></p>
<p>SpEL投影运算还支持Map投影，但Map投影最终只能得到List结果，如上所示，对于投影表达式中的“#this”将是Map.Entry，所以可以使用“value”来获取值，使用“key”来获取键。</p>
<p>集合选择</p>
<p>在SQL中指使用select进行选择行数据，而在SpEL指根据原集合通过条件表达式选择出满足条件的元素并构造为新的集合，SpEL使用“(list|map).?[选择表达式]”，其中选择表达式结果必须是boolean类型，如果true则选择的元素将添加到新集合中，false将不添加到新集合中。<br><figure class="highlight vhdl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">Collection&lt;<span class="typename">Integer</span>&gt; collection =<span class="keyword">new</span> ArrayList&lt;<span class="typename">Integer</span>&gt;();</span><br><span class="line">collection.add(<span class="number">4</span>);</span><br><span class="line">collection.add(<span class="number">5</span>);</span><br><span class="line">// ===============集合或数组测试 ==============</span><br><span class="line">EvaluationContext context1 =<span class="keyword">new</span> StandardEvaluationContext();</span><br><span class="line">context1.setVariable(<span class="string">"collection"</span>, collection);</span><br><span class="line">Collection&lt;<span class="typename">Integer</span>&gt; result1 = parser.parseExpression(<span class="string">"#collection.?[#this&gt;4]"</span>).getValue(context1, Collection.class);</span><br><span class="line"><span class="keyword">Assert</span>.assertEquals(<span class="number">1</span>, result1.size());</span><br><span class="line"><span class="keyword">Assert</span>.assertEquals(<span class="keyword">new</span> <span class="typename">Integer</span>(<span class="number">5</span>), result1.iterator().<span class="keyword">next</span>());</span><br><span class="line"><span class="keyword">Map</span>&lt;<span class="typename">String</span>, <span class="typename">Integer</span>&gt; <span class="keyword">map</span> =<span class="keyword">new</span> HashMap&lt;<span class="typename">String</span>, <span class="typename">Integer</span>&gt;();</span><br><span class="line"><span class="keyword">map</span>.put(<span class="string">"a"</span>, <span class="number">1</span>);</span><br><span class="line"><span class="keyword">map</span>.put(<span class="string">"b"</span>, <span class="number">2</span>);</span><br><span class="line">// =============== <span class="keyword">Map</span>测试 ==============</span><br><span class="line">EvaluationContext context2 =<span class="keyword">new</span> StandardEvaluationContext();</span><br><span class="line">context2.setVariable(<span class="string">"map"</span>, <span class="keyword">map</span>);</span><br><span class="line"><span class="keyword">Map</span>&lt;<span class="typename">String</span>, <span class="typename">Integer</span>&gt; result2 = parser.parseExpression(<span class="string">"#map.?[#this.key != 'a']"</span>).getValue(context2, <span class="keyword">Map</span>.class);</span><br><span class="line"><span class="keyword">Assert</span>.assertEquals(<span class="number">1</span>, result2.size());</span><br><span class="line"></span><br><span class="line">List&lt;<span class="typename">Integer</span>&gt; result3 = parser.parseExpression(<span class="string">"#map.?[key != 'a'].![value+1]"</span>).getValue(context2, List.class);</span><br><span class="line"><span class="keyword">Assert</span>.assertEquals(<span class="keyword">new</span> <span class="typename">Integer</span>(<span class="number">3</span>), result3.iterator().<span class="keyword">next</span>());</span><br></pre></td></tr></table></figure></p>
<p>对于Map选择，如“#map.?[#this.key != ‘a’]”将选择键值不等于”a”的，其中选择表达式中“#this”是Map.Entry类型，而最终结果还是Map，这点和投影不同；集合选择和投影可以一起使用，如“#map.?[key != ‘a’].![value+1]”将首先选择键值不等于”a”的，然后在选出的Map中再进行“value+1”的投影。</p>
<h4 id="表达式模板">表达式模板</h4><p>模板表达式就是由字面量与一个或多个表达式块组成。每个表达式块由“前缀+表达式+后缀”形式组成，如“${1+2}”即表达式块。在前边我们已经介绍了使用ParserContext接口实现来定义表达式是否是模板及前缀和后缀定义。在此就不多介绍了，如“Error ${井v0} ${井v1}”(把<code>井</code>换位<code>#</code>)表达式表示由字面量“Error ”、模板表达式“#v0”、模板表达式“#v1”组成，其中v0和v1表示自定义变量，需要在上下文定义。</p>

      
    </div>
    <footer class="article-footer">
	  
	  <!-- 百度分享 Start -->
	  <div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a><a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a><a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博"></a><a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网"></a><a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a></div>
	  <!-- 百度分享 End -->
	  
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Spring/">Spring</a></li></ul>

	  
<span>
Updated:<time datetime="2015-07-17T03:44:51.000Z" itemprop="dateModified">2015-07-17</time>
</span>


    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2015/03/13/jsp-servlet-note/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          JSP/Servlet及相关技术笔记
        
      </div>
    </a>
  
  
    <a href="/2015/03/06/spring-note-2/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">Spring笔记二</div>
    </a>
  
</nav>

  
</article>



<!-- 多说评论框 start -->

<section id="comments">
  <div class="ds-thread"  data-thread-key="/2015/03/06/spring-note-1/" data-title="Spring笔记一" data-url="http://howiefh.github.io/2015/03/06/spring-note-1/" id="ds_thread">
    <noscript>Please enable JavaScript to view the <a href="//duoshuo.com/?ref_noscript">comments powered by duoshuo.</a></noscript>
  </div>
</section>

<!-- 多说评论框 end -->
</section>
        
          
  <div id="toc" class="toc-aside">
  <h2 class="toc-title">Contents</h2>
    
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring核心机制：依赖注入"><span class="toc-number">1.</span> <span class="toc-text">Spring核心机制：依赖注入</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#设值注入"><span class="toc-number">1.1.</span> <span class="toc-text">设值注入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#构造注入"><span class="toc-number">1.2.</span> <span class="toc-text">构造注入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#两种注入方式的对比"><span class="toc-number">1.3.</span> <span class="toc-text">两种注入方式的对比</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring容器"><span class="toc-number">2.</span> <span class="toc-text">Spring容器</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#使用ApplicationContext"><span class="toc-number">2.1.</span> <span class="toc-text">使用ApplicationContext</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ApplicationContext的国际化支持"><span class="toc-number">2.2.</span> <span class="toc-text">ApplicationContext的国际化支持</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ApplicationContext的事件机制"><span class="toc-number">2.3.</span> <span class="toc-text">ApplicationContext的事件机制</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#让Bean获取Spring容器"><span class="toc-number">2.4.</span> <span class="toc-text">让Bean获取Spring容器</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring容器中的Bean"><span class="toc-number">3.</span> <span class="toc-text">Spring容器中的Bean</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Bean的基本定义"><span class="toc-number">3.1.</span> <span class="toc-text">Bean的基本定义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#容器中Bean的作用域"><span class="toc-number">3.2.</span> <span class="toc-text">容器中Bean的作用域</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#配置依赖"><span class="toc-number">3.3.</span> <span class="toc-text">配置依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#设置普通属性值"><span class="toc-number">3.4.</span> <span class="toc-text">设置普通属性值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#配置合作者"><span class="toc-number">3.5.</span> <span class="toc-text">配置合作者</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用自动装配注入合作者bean"><span class="toc-number">3.6.</span> <span class="toc-text">使用自动装配注入合作者bean</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#byName规则"><span class="toc-number">3.6.1.</span> <span class="toc-text">byName规则</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#byType规则"><span class="toc-number">3.6.2.</span> <span class="toc-text">byType规则</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#注入嵌套Bean"><span class="toc-number">3.7.</span> <span class="toc-text">注入嵌套Bean</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#list、set、map、props"><span class="toc-number">3.8.</span> <span class="toc-text">list、set、map、props</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#组合属性名称"><span class="toc-number">3.9.</span> <span class="toc-text">组合属性名称</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Spring的Bean和JavaBean"><span class="toc-number">3.10.</span> <span class="toc-text">Spring的Bean和JavaBean</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring_3-0提供的Java配置管理"><span class="toc-number">4.</span> <span class="toc-text">Spring 3.0提供的Java配置管理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Bean实例的创建方式及依赖配置"><span class="toc-number">5.</span> <span class="toc-text">Bean实例的创建方式及依赖配置</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#使用构造器创建Bean实例"><span class="toc-number">5.1.</span> <span class="toc-text">使用构造器创建Bean实例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用静态工厂方法创建Bean"><span class="toc-number">5.2.</span> <span class="toc-text">使用静态工厂方法创建Bean</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#调用实例工厂方法创建Bean"><span class="toc-number">5.3.</span> <span class="toc-text">调用实例工厂方法创建Bean</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#深入理解容器中的Bean"><span class="toc-number">6.</span> <span class="toc-text">深入理解容器中的Bean</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#使用抽象Bean"><span class="toc-number">6.1.</span> <span class="toc-text">使用抽象Bean</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用子Bean"><span class="toc-number">6.2.</span> <span class="toc-text">使用子Bean</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Bean继承与Java继承的区别"><span class="toc-number">6.3.</span> <span class="toc-text">Bean继承与Java继承的区别</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#容器中的_工厂Bean"><span class="toc-number">6.4.</span> <span class="toc-text">容器中的 工厂Bean</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#获得Bean部署时的id"><span class="toc-number">6.5.</span> <span class="toc-text">获得Bean部署时的id</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#强制初始化Bean"><span class="toc-number">6.6.</span> <span class="toc-text">强制初始化Bean</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#容器中Bean的生命周期"><span class="toc-number">7.</span> <span class="toc-text">容器中Bean的生命周期</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#依赖关系注入之后的行为"><span class="toc-number">7.1.</span> <span class="toc-text">依赖关系注入之后的行为</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Bean_销毁之前的行为"><span class="toc-number">7.2.</span> <span class="toc-text">Bean 销毁之前的行为</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#协调作用域不同步的Bean"><span class="toc-number">7.3.</span> <span class="toc-text">协调作用域不同步的Bean</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#深入理解依赖关系配置"><span class="toc-number">8.</span> <span class="toc-text">深入理解依赖关系配置</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#注入其他Bean的属性值"><span class="toc-number">8.1.</span> <span class="toc-text">注入其他Bean的属性值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#注入其他Bean的Field值"><span class="toc-number">8.2.</span> <span class="toc-text">注入其他Bean的Field值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#注入其他Bean的方法返回值"><span class="toc-number">8.3.</span> <span class="toc-text">注入其他Bean的方法返回值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#基于xml_schema_的简化配置方式"><span class="toc-number">9.</span> <span class="toc-text">基于xml schema 的简化配置方式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#使用p名称空间配置属性"><span class="toc-number">9.1.</span> <span class="toc-text">使用p名称空间配置属性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用util_Schema"><span class="toc-number">9.2.</span> <span class="toc-text">使用util Schema</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring3-0提供的表达式语言(SpEl)"><span class="toc-number">10.</span> <span class="toc-text">Spring3.0提供的表达式语言(SpEl)</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#使用Expression接口进行表达式求值"><span class="toc-number">10.1.</span> <span class="toc-text">使用Expression接口进行表达式求值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Bean定义中的表达式语言支持"><span class="toc-number">10.2.</span> <span class="toc-text">Bean定义中的表达式语言支持</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#SpEL语法详述"><span class="toc-number">10.3.</span> <span class="toc-text">SpEL语法详述</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#基本表达式"><span class="toc-number">10.3.1.</span> <span class="toc-text">基本表达式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#类相关表达式"><span class="toc-number">10.3.2.</span> <span class="toc-text">类相关表达式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#集合相关表达式"><span class="toc-number">10.3.3.</span> <span class="toc-text">集合相关表达式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#表达式模板"><span class="toc-number">10.3.4.</span> <span class="toc-text">表达式模板</span></a></li></ol></li></ol></li></ol>
    
  </div>

<aside id="sidebar">

  
    
<div class="widget-wrap">
  <h3 class="widget-title">ABOUT ME</h3>
  <ul class="widget about-me">
    
    <li><img class="author" title="About me" src="http://fh-1.qiniudn.com/okal-eltocat.jpg" /></li>
    
    
    <li>Hi,I'm FengHao.</li>
    
    <li>I'll share something interesting and my learning experience with you at this blog.</li>
    
    <li>前博客:<a href="http://hi.baidu.com/idea_star" target="_BLANK">百度空间</a></li>
    
  </ul>
</div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Categories</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Android/">Android</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/C/">C</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Database/">Database</a><span class="category-list-count">13</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/Database/MongoDB/">MongoDB</a><span class="category-list-count">10</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Database/MySQL/">MySQL</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/Eclipse/">Eclipse</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/FTP/">FTP</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Git/">Git</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Hexo/">Hexo</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Java/">Java</a><span class="category-list-count">20</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/Java/FreeMarker/">FreeMarker</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Java/Shiro/">Shiro</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/">JavaEE</a><span class="category-list-count">4</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/Hibernate/">Hibernate</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/JSP/">JSP</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/Spring/">Spring</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaScript/">JavaScript</a><span class="category-list-count">5</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/JavaScript/jQuery/">jQuery</a><span class="category-list-count">1</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/Linux/">Linux</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/PHP/">PHP</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Suse/">Suse</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Ubuntu/">Ubuntu</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Vim/">Vim</a><span class="category-list-count">8</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/编程/">编程</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/软件/">软件</a><span class="category-list-count">1</span></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/Android/" style="font-size: 14.75px; color: #65bfa7">Android</a> <a href="/tags/C/" style="font-size: 13.88px; color: #71c1c2">C</a> <a href="/tags/CAS/" style="font-size: 13px; color: #7dc3de">CAS</a> <a href="/tags/Chrome/" style="font-size: 13px; color: #7dc3de">Chrome</a> <a href="/tags/Clean-Code/" style="font-size: 13.88px; color: #71c1c2">Clean Code</a> <a href="/tags/Database/" style="font-size: 13px; color: #7dc3de">Database</a> <a href="/tags/Eclipse/" style="font-size: 13px; color: #7dc3de">Eclipse</a> <a href="/tags/FTP/" style="font-size: 13.88px; color: #71c1c2">FTP</a> <a href="/tags/FreeMarker/" style="font-size: 14.75px; color: #65bfa7">FreeMarker</a> <a href="/tags/Gcc/" style="font-size: 13px; color: #7dc3de">Gcc</a> <a href="/tags/Git/" style="font-size: 14.75px; color: #65bfa7">Git</a> <a href="/tags/Github-Pages/" style="font-size: 13px; color: #7dc3de">Github Pages</a> <a href="/tags/Hexo/" style="font-size: 14.75px; color: #65bfa7">Hexo</a> <a href="/tags/Hibernate/" style="font-size: 13px; color: #7dc3de">Hibernate</a> <a href="/tags/JSP/" style="font-size: 13px; color: #7dc3de">JSP</a> <a href="/tags/JVM/" style="font-size: 14.75px; color: #65bfa7">JVM</a> <a href="/tags/Java/" style="font-size: 14.75px; color: #65bfa7">Java</a> <a href="/tags/JavaMail/" style="font-size: 13px; color: #7dc3de">JavaMail</a> <a href="/tags/JavaScript/" style="font-size: 16.5px; color: #4dbc6f">JavaScript</a> <a href="/tags/Linux/" style="font-size: 13.88px; color: #71c1c2">Linux</a> <a href="/tags/Log/" style="font-size: 13px; color: #7dc3de">Log</a> <a href="/tags/Markdown/" style="font-size: 13.88px; color: #71c1c2">Markdown</a> <a href="/tags/MongoDB/" style="font-size: 20px; color: #1db400">MongoDB</a> <a href="/tags/MySQL/" style="font-size: 13.88px; color: #71c1c2">MySQL</a> <a href="/tags/PHP/" style="font-size: 16.5px; color: #4dbc6f">PHP</a> <a href="/tags/Rhythmbox/" style="font-size: 13px; color: #7dc3de">Rhythmbox</a> <a href="/tags/SSO/" style="font-size: 13px; color: #7dc3de">SSO</a> <a href="/tags/Servlet/" style="font-size: 13px; color: #7dc3de">Servlet</a> <a href="/tags/Shiro/" style="font-size: 13.88px; color: #71c1c2">Shiro</a> <a href="/tags/Spring/" style="font-size: 13.88px; color: #71c1c2">Spring</a> <a href="/tags/Suse/" style="font-size: 13px; color: #7dc3de">Suse</a> <a href="/tags/Thinking-in-Java/" style="font-size: 19.13px; color: #29b61c">Thinking in Java</a> <a href="/tags/Ubuntu/" style="font-size: 17.38px; color: #41ba53">Ubuntu</a> <a href="/tags/Vim/" style="font-size: 18.25px; color: #35b838">Vim</a> <a href="/tags/VirtualBox/" style="font-size: 13px; color: #7dc3de">VirtualBox</a> <a href="/tags/Vsftpd/" style="font-size: 13px; color: #7dc3de">Vsftpd</a> <a href="/tags/jQuery/" style="font-size: 13px; color: #7dc3de">jQuery</a> <a href="/tags/pam-mysql/" style="font-size: 13px; color: #7dc3de">pam_mysql</a> <a href="/tags/小米/" style="font-size: 13px; color: #7dc3de">小米</a> <a href="/tags/软件/" style="font-size: 15.63px; color: #59bd8b">软件</a>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/09/">September 2015</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/08/">August 2015</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/07/">July 2015</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/05/">May 2015</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/04/">April 2015</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/03/">March 2015</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/02/">February 2015</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/12/">December 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/11/">November 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/10/">October 2014</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/09/">September 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/08/">August 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/07/">July 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/06/">June 2014</a><span class="archive-list-count">6</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/05/">May 2014</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/04/">April 2014</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/03/">March 2014</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/02/">February 2014</a><span class="archive-list-count">11</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/01/">January 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/12/">December 2013</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/11/">November 2013</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/08/">August 2013</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/07/">July 2013</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/06/">June 2013</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/05/">May 2013</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/04/">April 2013</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/03/">March 2012</a><span class="archive-list-count">1</span></li></ul>
    </div>
  </div>


  
    <div class="widget-wrap">
  <h3 class="widget-title">Calendar</h3>
  <div class="widget">
    <div id="g-calendar" class="g-calendar">
        <span class="g-calendar-prev"></span>
		 
        <span class="g-calendar-back"></span>
        <span class="g-calendar-now"></span>
		 
        <span class="g-calendar-next"></span>
        <div class="g-calendar-hd"></div>
        <div class="g-calendar-tit"></div>
        <div class="g-calendar-bd"></div>
    </div>
  </div>
</div>
<script type="text/javascript">
function LGY_calendar(wrapId, options){
    this.oWrap = this.getId(wrapId);
    this.oHead = this.getByClassName('g-calendar-hd',this.oWrap)[0];
    this.oBody = this.getByClassName('g-calendar-bd',this.oWrap)[0];
    this.oTit = this.getByClassName('g-calendar-tit',this.oWrap)[0];
    this.oPrev = this.getByClassName('g-calendar-prev',this.oWrap)[0];
    this.oNext = this.getByClassName('g-calendar-next',this.oWrap)[0];
    this.oNow = this.getByClassName('g-calendar-now',this.oWrap)[0];
    this.oBack = this.getByClassName('g-calendar-back',this.oWrap)[0];
    this.init();
}
LGY_calendar.prototype = {
    ///////////获取ID元素
    getId:function(id){
        return document.getElementById(id);
    },
    ////////获取css类名元素
    getByClassName:function(className,parent){
        var elem = [],
            node = parent != undefined&&parent.nodeType==1?parent.getElementsByTagName('*'):document.getElementsByTagName('*'),
            p = new RegExp("(^|\\s)"+className+"(\\s|$)");
        for(var n=0,i=node.length;n<i;n++){
            if(p.test(node[n].className)){
                elem.push(node[n]);
            }
        }
        return elem;
    },
    //填充日历
    fillDate:function(year,month){
        //本月份第一天是星期几-为显示上个月的天数做铺垫
        var first_day = new Date(year,month,1).getDay(),
        //如果刚好是星期天，则空出一行（显示上个月的天数）
            first_day = first_day == 0?first_day=7:first_day;
        //本月份最后一天是几号
        var final_date = new Date(year,month+1,0).getDate(),
        //上个月的最后一天是几号
            last_date = new Date(year,month,0).getDate(),
        //剩余的格子数--即排在末尾的格子数
            surplus = 42 - first_day - final_date;
        //设置年的链接
        var yearHead = "<a href='/" + "archives/" + year + "/'>" + year + " "+ "</a>"; 
        //设置年的链接
        var monthHead = "";
        var month1 = month + 1;
        if (month1 < 10) {
            monthHead = "<a href='/" + "archives/" + year + "/" + "0" + month1 + "/'>" + " " + month1 + " " + "</a>";
        } else {
            monthHead = "<a href='/" + "archives/" + year + "/" + month1 + "/'>" + " " + month1 + " " + "</a>";
        }
        //设置表头的日历
        this.oHead.innerHTML = yearHead+'年'+monthHead+'月';
        //填充日历执行
        var html = '';
        //上个月的显示天数
        for(var i=0;i<first_day;i++){
            html+='<span class="g-calendar-grey">'+(last_date-(first_day-1)+i)+'</span>';
        }
        //本月的显示天数
        var postdate = new Date("Fri Mar 06 2015 16:09:20 GMT+0800"); 
        if (true && postdate.getFullYear() == year && postdate.getMonth() == month) { 
            html += '<span>1</span><span>2</span><span>3</span><span>4</span><span><a href="/2015/03/05/hibernate-note/" title="Hibernate笔记">5</a></span><span><a href="/2015/03/06/spring-note-2/" title="当天有2篇博客,第一篇:Spring笔记二">6</a></span><span>7</span><span>8</span><span>9</span><span>10</span><span>11</span><span>12</span><span><a href="/2015/03/13/jsp-servlet-note/" title="JSP/Servlet及相关技术笔记">13</a></span><span>14</span><span>15</span><span>16</span><span>17</span><span>18</span><span>19</span><span>20</span><span>21</span><span>22</span><span>23</span><span>24</span><span>25</span><span>26</span><span>27</span><span>28</span>';
        } else {
            for(var j=0;j<final_date;j++){        
                html+='<span id="d'+(j+1)+'">'+(j+1)+'</span>';
            }
        }
        //下个月的显示天数
        for(var k=0;k<surplus;k++){
            html+='<span class="g-calendar-grey">'+(k+1)+'</span>';
        }
        //fill
        this.oBody.innerHTML = html;
        // 当前状态
        if(year==this.c_year&&this.c_month==month){
            this.oBody.getElementsByTagName('span')[first_day+this.date-1].className='g-calendar-on';
        }

        // 对所有文章遍历,然后将有文章的日期加上链接,如果文章太多的话,生成页面会很大,去掉了
        
    },
    // next切换
    next:function(){
        var _that = this;
        this.oNext.onclick = function(){
            _that.month++;
            if(_that.month>11){
                _that.month = 0;
                _that.year++;
            }
            // 填充日历
            _that.fillDate(_that.year,_that.month);
        };
    },
    // back 切换
    back:function(){
        var _that = this;
        if(this.oBack != undefined) {
            this.oBack.onclick = function(){
                var postdate = new Date("Fri Mar 06 2015 16:09:20 GMT+0800"); 
                _that.year = postdate.getFullYear();
                _that.month = postdate.getMonth();
                // 填充日历
                _that.fillDate(_that.year,_that.month);
            };
        }
    },
    // now切换
    now:function(){
        var _that = this;
        if(this.oNow != undefined ) {
            this.oNow.onclick = function(){
                var nowDate = new Date(); 
                _that.year = nowDate.getFullYear();
                _that.month = nowDate.getMonth();
                // 填充日历
                _that.fillDate(_that.year,_that.month);
            };
        }
    },
    // prev切换
    prev:function(){
        var _that = this;
        this.oPrev.onclick = function(){
            _that.month--;
            if(_that.month<0){
                _that.month = 11;
                _that.year--;
            }
            // 填充日历
            _that.fillDate(_that.year,_that.month);
        };
    },
    init:function(){
        this.oTit.innerHTML = '<span>日</span><span>一</span><span>二</span><span>三</span><span>四</span><span>五</span><span>六</span>';
        // 获取今天的日历时间
        var now = new Date();
        this.c_year = this.year = now.getFullYear();
        this.c_month = this.month = now.getMonth();
        this.date = now.getDate();
        // 初始化--填充日历
        this.fillDate(this.year,this.month);
        //next切换
        this.next();
        //prev切换
        this.prev();
        //back 切换
        this.back();
        //now 切换
        this.now();
    }
}
new LGY_calendar('g-calendar');
</script>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2015/09/01/javascript-summary/">JavaScript 总结</a>
          </li>
        
          <li>
            <a href="/2015/08/28/javascript-oop-function-expression-and-async/">JavaScript 面向对象程序设计、函数表达式和异步编程</a>
          </li>
        
          <li>
            <a href="/2015/08/28/javascript-reference-type/">JavaScript 引用类型</a>
          </li>
        
          <li>
            <a href="/2015/08/28/javascript-grammar/">JavaScript 基本语法</a>
          </li>
        
          <li>
            <a href="/2015/08/10/java-web/">Java Web 笔记</a>
          </li>
        
      </ul>
    </div>
  </div>


  
    
<div class="widget-wrap">
  <h3 class="widget-title">Recent Comments</h3>
  <ul class="widget ds-recent-comments" data-num-items="5" data-show-avatars="0" data-show-title="1" data-show-time="1"></ul>
</div>
<!-- 需要多说的公用代码 -->


  

</aside>

        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2015 howiefh<br>
      Powered by <a href="http://zespia.tw/hexo/" target="_blank">Hexo</a> and Theme by <a href="https://github.com/howiefh/hexo-theme-landscape-f" target="_blank" title="Landscape-F">Landscape-F</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<!-- 多说公共JS代码 start (一个网页只需插入一次) -->

<script type="text/javascript">
  var duoshuoQuery = {short_name:"howiefh"};
  (function() {
	var ds = document.createElement('script');
	ds.type = 'text/javascript';ds.async = true;
	ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
	ds.charset = 'UTF-8';
	(document.getElementsByTagName('head')[0] 
		|| document.getElementsByTagName('body')[0]).appendChild(ds);
  })();
</script> 

<!-- 多说公共JS代码 end -->

<!-- 百度分享 start -->

<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":["mshare","douban","bdysc","sqq","qq","hi","baidu","huaban","youdao","sdo","mail","xg","diandian","fx","copy","print"],"bdPic":"","bdStyle":"1","bdSize":"16"},"share":{},"image":{"viewList":["qzone","tsina","tqq","renren","weixin"],"viewText":"分享到：","viewSize":"16"}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>

<!-- 百度分享 end -->

<!--
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="/js/jquery.min.js"></script>
-->
<script src="/js/jquery.min.js" type="text/javascript"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css" type="text/css">
  <script src="/fancybox/jquery.fancybox.pack.js" type="text/javascript"></script>


<div class="bottom-btn">

	<a class="icon-gotop" href="javascript:void(0)" title="返回顶部"></a>
	<script src="/js/gotop.js" type="text/javascript"></script>
	<!--
	<script src="/js/gotop.js"></script>
	-->


	<a class="icon-toc-toggle" href="javascript:void(0)" title="文章目录"></a>
	<!--
	<script src="/js/toc_aside_toggle.js"></script>
	-->

</div>
<script src="/js/toc_aside_toggle.js" type="text/javascript"></script>


<script src="/js/script.js" type="text/javascript"></script>

  </div>
</body>
</html>
